| #!/usr/bin/perl |
| # Licensed to the Apache Software Foundation (ASF) under one or more |
| # contributor license agreements. See the NOTICE file distributed with |
| # this work for additional information regarding copyright ownership. |
| # The ASF licenses this file to You under the Apache License, Version 2.0 |
| # (the "License"); you may not use this file except in compliance with |
| # the License. You may obtain a copy of the License at |
| # |
| # http://www.apache.org/licenses/LICENSE-2.0 |
| # |
| # Unless required by applicable law or agreed to in writing, software |
| # distributed under the License is distributed on an "AS IS" BASIS, |
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| # See the License for the specific language governing permissions and |
| # limitations under the License. |
| |
| # Reads any number of file names from the command line, then split()s |
| # STDIN on tabs and writes them to those files. Example usage: |
| # |
| # paste file1 file2 file3 ... | split2files file1.new file2.new file3.new.gz ... |
| # |
| # If there are more fields on STDIN that files on the command-line, the extra |
| # fields are silently discarded. |
| # |
| # A common usage scenario is to paste together parallel lines and do some filtering, |
| # then write out to a new set of files (thus retaining parallelization). |
| |
| use FileHandle; |
| |
| my @fh; |
| $| = 1; # don't buffer output |
| |
| if (@ARGV < 0) { |
| print "Usage: cat tabbed-file | split2files file1 [file2 [file3 ...]]\n"; |
| exit; |
| } |
| |
| my @fh = map { get_filehandle($_) } @ARGV; |
| @ARGV = (); |
| |
| while (my $line = <>) { |
| chomp($line); |
| my (@fields) = split(/\t/, $line); |
| |
| map { print {$fh[$_]} "$fields[$_]\n" } (0..$#fh); |
| } |
| |
| sub get_filehandle { |
| my $file = shift; |
| |
| if ($file eq "-") { |
| return *STDOUT; |
| } else { |
| local *FH; |
| open FH, ">$file" or die "can't open '$file' for writing"; |
| return *FH; |
| } |
| } |