Advertisement
overloop

tailhead.pl

Aug 25th, 2014
307
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.08 KB | None | 0 0
  1. #!/usr/bin/perl
  2.  
  3. sub usage {
  4.     print "usage:\n " . $0 . " tail_lines head_lines file1 file2 .. fileN\n";
  5.     print "example - output lines 20..15 from end of file:\n " . $0 . " 20 5 file{1,2}.txt\n";
  6.     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";
  7. }
  8.  
  9. my ($tail, $head, @files) = @ARGV;
  10.  
  11. if (scalar(@ARGV) == 0 || (scalar(@ARGV)>0 && ($ARGV[0] eq '-h' || $ARGV[0] eq '--help'))) {
  12.     usage;
  13.     exit(0);
  14. }
  15.  
  16. if (scalar(@ARGV)<2) {
  17.     print "error: need more arguments\n";
  18.     usage;
  19.     exit(-1);
  20. }
  21.  
  22. if (scalar(@files)==0) {
  23.     print "error: no files\n";
  24.     usage;
  25.     exit(-1);
  26. }
  27.  
  28. if ($head > $tail) {
  29.     print "error: head_lines>tail_lines\n";
  30.     usage;
  31.     exit(-1);
  32. }
  33.  
  34.  
  35. for my $file (@files) {
  36.     if ( -f $file) {
  37.         #tail is optimized and works faster on big files than open INPUT,"<",$file; my @lines = <INPUT>; close INPUT
  38.         my $lines = `tail -n $tail $file`;
  39.         my @lines = split("\n",$lines);
  40.         @lines = splice(@lines,0,$head);
  41.         print "==> " . $file . " <==\n" if (scalar(@files)>1);
  42.         print $_ . "\n" for @lines;
  43.     }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement