![]() |
Hello and Welcome from United States to the UNIX and Linux Forums! Thank You for Visiting and Joining Our Global Community.
|
|
google unix.com
|
|||||||
| Forums | Register | Forum Rules | Links | Albums | FAQ | Members List | Calendar | Search | Today's Posts | Mark Forums Read |
| Shell Programming and Scripting Post questions about KSH, CSH, SH, BASH, PERL, PHP, SED, AWK and OTHER shell scripts and shell scripting languages here. |
More UNIX and Linux Forum Topics You Might Find Helpful
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| grep and display few lines before and after | melanie_pfefer | SUN Solaris | 13 | 02-19-2009 11:54 PM |
| grep + lines after | Janus | Shell Programming and Scripting | 4 | 11-03-2006 05:56 PM |
| grep string & next n lines | ashterix | Shell Programming and Scripting | 8 | 11-21-2005 11:38 PM |
| Grep on multiple lines | gundu | Shell Programming and Scripting | 13 | 03-25-2005 02:43 PM |
![]() |
|
|
LinkBack | Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
||||
|
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. |
|
||||
|
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 |
|
||||
|
hope below perl can help you some
Code:
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
|
| Sponsored Links | ||
|
|
![]() |
| Bookmarks |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|