grep -n lines before and after

Hi,

is it possible to grep a pattern that will include the "n" lines before and after the line where the pattern have been found?

e.g.

#this contains the test.file
line1
line2
line3
line4
line5

then a grep command to search the word "line3"
and the output should be 1 (or n) line before that line and 1 (or n) line "after" that line.

dessired output of the grep command

line2
line3
line4

Thanks in advance.

If you have GNU grep, then it is possible. From man grep

       -A NUM, --after-context=NUM
              Print NUM lines  of  trailing  context  after  matching  lines.
              Places  a  line  containing  --  between  contiguous  groups of
              matches.

       -B NUM, --before-context=NUM
              Print  NUM  lines  of  leading  context  before matching lines.
              Places a  line  containing  --  between  contiguous  groups  of
              matches.

Hi,

There is a very simple way of doing this. Lets say you have a file test.txt having 'view' in some line. Say, you wish to get 5 lines above and below the line containing 'view' and output to a file say test_one.txt use the following:

grep -C 5 "view" test.txt > test_one.txt

Regards,
Sumedha

Please note: a lot of these examples ONLY work with GNU tools, not all versions of grep.

hope below perl can help you some

sub lines_grep{
my($pattern,$line,$flag,$n,@tmp)=(@_);
while(<DATA>){
	if($_=~/$pattern/){
		print @tmp;	
		$flag=1;
	}
	else{
		if($#tmp < $line-1){
			push @tmp, $_;
		}
		else{
			shift @tmp;
			push @tmp, $_;
		}
	}
	if ($flag==1){
		print $_ ;
		$n++;
	}
	if($n>$line){
		last;
	}
}
}
#lines_grep(pattern,3);
lines_grep(4,2);
__DATA__
1
2
3
4
pattern
6
7
8
9