-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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