Skip to content

Instantly share code, notes, and snippets.

@briandfoy
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save briandfoy/8af92ac34c36f100b1dc to your computer and use it in GitHub Desktop.
Save briandfoy/8af92ac34c36f100b1dc to your computer and use it in GitHub Desktop.
#!/usr/bin/env perl
use strict;
no strict 'refs';
my ($VERSION) = '$Revision: 1.2 $' =~ /([.\d]+)/;
my (@fh, $i);
my @sep = ( "\t" );
my $dash_ess = 0;
exit if not @ARGV;
while ($ARGV[0] =~ /^-[^=]+$/) {
$_ = shift @ARGV;
/^-\?$/ and do { print <<EOF;
Usage: $0 [-s] [-d list] file...
Merges the corresponding lines of files.
EOF
exit;
};
/^-d$/ and do {
my $arg = shift;
@sep = split(//, eval qq{sprintf("$arg")});
next;
};
/^-s$/ and do { $dash_ess = 1; next; }
}
for $i (0..$#ARGV) {
$fh[$i] = "F$i";
my( $name, $line ) = $ARGV[$i] =~ /(.*?) (?: = ([0-9]+) )? \z/x;
print "$fh[$i] $name $line\n";
open($fh[$i], $name) or die "$0: cannot open $name";
if( defined $line ) {
tell( $fh[$i] );
readline( $fh[$i] ) while $. < $line - 1
}
}
if ($dash_ess) {
foreach $i (0..$#fh) {
my $fh;
$fh = $fh[$i];
my $current_sep = 0;
my $tline;
while(<$fh>) {
chomp;
$tline .= $_ . $sep[$current_sep++];
$current_sep = 0 if $current_sep == scalar @sep;
}
print "$tline\n";
close $fh;
}
exit;
}
my $files_still_open = 1;
while (1) {
my $current_sep = 0;
$files_still_open = 0;
foreach $i (0..$#fh) {
$files_still_open = 1 if not eof $fh[$i];
}
last if not $files_still_open;
my $tline;
foreach $i (0..$#fh) {
if (not eof $fh[$i]) {
my $fh;
$fh = $fh[$i];
my $line = <$fh>;
chomp($line);
$tline .= $line;
}
$tline .= "$sep[$current_sep++]" if $i != $#fh;
$current_sep = 0 if $current_sep == scalar @sep;
}
print "$tline\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment