-3

I am trying to print 5 lines above "END" from a huge data file.

Can anyone please help? My file format is

 --   Count .    .    .     . . .   .   .   .   .   .   . . . . . . . . . . . .  -------------------------------------    ------------------------------------------- 
00000001 0000 0000 00000 2 0 01c 01d 01c 01d 01c 01d 0 1 0 1 0 0 0 0 0 0 0 00 
00000002 0001 0000 00000 2 2 019 006 019 006 019 006 0 1 1 1 1 1 1 1 1 1 0 00
00000003 0002 0000 00000 2 0 00d 007 00d 007 00d 007 0 0 0 1 0 0 0 0 0 0 0 00
00000004 0003 0000 00000 2 2 00b 009 00b 009 00b 009 0 0 0 0 0 0 0 0 0 0 0 00 
00000005 0004 0000 00000 2 2 01a 008 01a 008 01a 008 0 0 0 0 0 0 0 0 0 0 0 00
END

~

  • Can you please show the examples you refer to? We don't see any operator `[$#i]` here. The construct `$#i` is the index of the last element of an array `@i`, e.g. `@i = (100, 200, 300);` yields `$#i == 2`. – PerlDuck Sep 12 '16 at 18:06
  • For example : http://www.perlmonks.org/?node_id=983672 "$#lines" – eshan kanoje Sep 12 '16 at 18:09
  • 4
    What have you tried so far? Please edit your question to include a complete minimal code example and small test file that can be used to help you solve your issue. Please include the information you obtained and the expected results. Otherwise we're just guessing. Thanks – David Harris Sep 12 '16 at 18:09
  • Sorry. I feel the question is more clear now – eshan kanoje Sep 12 '16 at 18:11
  • 1
    Please include the code you have tried – Borodin Sep 12 '16 at 18:16
  • A regex alternative: https://regex101.com/r/jF3jN7/1 – Jan Sep 12 '16 at 21:33

2 Answers2

2

Just use grep:

grep END file -B 5

Alternatively, you can use either of the following Perl one-liners:

perl -ne'print @a if /^END$/; push @a, $_; shift(@a) if @a>5;' file

or

perl -ne'push @a, $_; print @a if /^END$/; shift(@a) if @a>5;' file

The second prints the matching line, which the first one does not.

ikegami
  • 367,544
  • 15
  • 269
  • 518
Dave Grabowski
  • 1,619
  • 10
  • 19
  • I need to use this in my script its a smart part then I need to perform operation on that. Can you please suggest in the form of perl script – eshan kanoje Sep 12 '16 at 18:16
  • If this has to be in perl then show what you have tried so far. – Dave Grabowski Sep 12 '16 at 18:22
  • You can also run it inside a script using backticks to store the output in a variable. More info that might be helpful in this SO question: http://stackoverflow.com/questions/3854651/how-can-i-store-the-result-of-a-system-command-in-a-perl-variable – yoniyes Sep 12 '16 at 19:54
1

Just keep the last 5 lines you've read in memory.

my $found = 0;
my @buf;
while (<>) {
   if (/^END$/) {
       $found = 1;
       last;
   }

   push(@buf, $_);
   shift(@buf) if @buf > 5;
}

print(@buf) if $found;
ikegami
  • 367,544
  • 15
  • 269
  • 518