Skip to content

Instantly share code, notes, and snippets.

@mjpost
Created March 19, 2014 17:34
Show Gist options
  • Save mjpost/9647010 to your computer and use it in GitHub Desktop.
Save mjpost/9647010 to your computer and use it in GitHub Desktop.
UNIX has `head` and `tail`, but what about when you need a line number in the middle? `mid` provides just that.
#!/usr/bin/perl
# Returns the requested line number from a file or list of files.
# If the line number is given as i:j or i-j, selects that range.
# If no file is given, we read from STDIN.
my $arg = shift;
($num1,$split,$num2) = split(/([:\-\+])/,$arg);
die usage() unless $arg and (! $split or $num2);
my $i = $num1;
my $j = ($split)
? ( ($split eq "+") ? ($num1 + $num2) : ($num2) )
: $num1;
exit usage() unless $i > 0;
if (@ARGV > 1) {
# if multiple files are given, recurse to calling mid on each one
map { system("$0 $i $_") } @ARGV;
} else {
# else, just print the ith line
while (my $line = <>) {
next if $. < $i;
print $line;
last if $. >= $j;
}
}
sub usage() {
print STDERR <<EOF;
Usage:
mid LINENO FILE1 [FILE2 FILE3 ...]
cat FILE | mid LINENO
where LINENO is the line number of the file (starting with 1).
EOF
exit(1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment