Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/perl
- sub usage {
- print "usage:\n " . $0 . " tail_lines head_lines file1 file2 .. fileN\n";
- print "example - output lines 20..15 from end of file:\n " . $0 . " 20 5 file{1,2}.txt\n";
- print "same as:\n for i in file{1,2}.txt; do\n echo \"==> \$i <==\"; cat \$i tail -n 20 | head -n 5\n done\n";
- }
- my ($tail, $head, @files) = @ARGV;
- if (scalar(@ARGV) == 0 || (scalar(@ARGV)>0 && ($ARGV[0] eq '-h' || $ARGV[0] eq '--help'))) {
- usage;
- exit(0);
- }
- if (scalar(@ARGV)<2) {
- print "error: need more arguments\n";
- usage;
- exit(-1);
- }
- if (scalar(@files)==0) {
- print "error: no files\n";
- usage;
- exit(-1);
- }
- if ($head > $tail) {
- print "error: head_lines>tail_lines\n";
- usage;
- exit(-1);
- }
- for my $file (@files) {
- if ( -f $file) {
- #tail is optimized and works faster on big files than open INPUT,"<",$file; my @lines = <INPUT>; close INPUT
- my $lines = `tail -n $tail $file`;
- my @lines = split("\n",$lines);
- @lines = splice(@lines,0,$head);
- print "==> " . $file . " <==\n" if (scalar(@files)>1);
- print $_ . "\n" for @lines;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement