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.
Asked
Active
Viewed 3,106 times
-1
-
4use grep with `-C 5` option – perreal Jul 11 '13 at 08:31
-
as you want it perl: [ack](http://beyondgrep.com/) – salva Jul 11 '13 at 08:37
-
Welcome to SO. Here, take the [tour](http://stackoverflow.com/about). – Steve P. Jul 11 '13 at 09:47
-
It is very difficult to answer questions if there is: 1) no code, 2) no input data, and 3) no expected results. – shawnhcorey Jul 11 '13 at 12:47
-
possible duplicate of http://stackoverflow.com/questions/1523846/how-can-i-print-a-matching-line-one-line-immediately-above-it-and-one-line-imme – jvilhena Jul 11 '13 at 15:11
2 Answers
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