-1

I have a Folder with multiple .txt files in it. I want to check few strings in those text files and give output as a out.txt with 5 lines above and 5 lines below of the located string.

Luna Junsay
  • 3
  • 1
  • 2

2 Answers2

2

It is easier to do with grep:

grep -A 5 -B 5 'searchstring' *.txt > a.out

With Perl :-)

use strict;use warnings;
`grep -A 5 -B 5 'searchstring' *.txt > a.out`;
die "Something went wrong: $!" if $?;
user1126070
  • 5,059
  • 1
  • 16
  • 15
1

if you insist on a perl oneliner;

perl -n -e 'if (/searchStringHere/) {print "\n\n\n\n\n$_\n\n\n\n\n"}' *.txt

If the grep solution works for you, i consider it to be more elegant...

update

it just struck me that you might be a windows user, so you don't have grep...

this code was not tested, as i don't have perl installed on this machine, but it should work: !#yourperl/perl

$flag, $l1, $l2, $l3, $l4, $l5, $l6;
$cnt = 5;
$file = shift;
open("$file") || die "can't open $file\n";
while (<>) {
 $l1 = $l2; # starting with reserving the lines for back print
 $l2 = $l3;
 $l4 = $l5;
 $l5 = $l6;
 $l6 = $_;
 if (/your string here/) {
   $cnt = 5;
   print ($l1$l2$l3$l4$l5$l6);# print line + 5 prev lines
   next
 }
 if ($cnt >0) { # print the next 5 lines
    print $l6;
    $cnt--;
 } 
}
user2141046
  • 862
  • 2
  • 7
  • 21
  • please notice that if you intend on finding again and again you only need one set of \n\n\n\n\n - the other will be generated by the next search result. if you leave it as is, you will have 10 lines between each two results in the middle of your find list. – user2141046 Jul 11 '13 at 09:00
  • As I understand the question, the OP wants the context around the key word to search. Not blank lines. – Birei Jul 11 '13 at 09:00
  • oh, so I misunderstood what he meant. in that case the grep -C does it perfectly – user2141046 Jul 11 '13 at 10:57