Go Back   The UNIX and Linux Forums > Top Forums > UNIX for Dummies Questions & Answers


UNIX for Dummies Questions & Answers If you're not sure where to post a UNIX or Linux question, post it here. All UNIX and Linux newbies welcome !!

Closed Thread    
 
Thread Tools Search this Thread Display Modes
    #1  
Old 06-19-2012
saj saj is offline
Registered User
 
Join Date: Apr 2011
Posts: 29
Thanks: 4
Thanked 0 Times in 0 Posts
Printing nth and n+1th line after a pattern match

Hi ,
I want to print the nth and n+1 lines from a file once it gets a pattern match.
For eg:

aaa
bbb
ccc
ddd
gh
jjjj

If I find a match for bbb then I need to print bbb as well as 3rd and 4th line from the match.. Please help..Is it possible to get a command using sed
Sponsored Links
    #2  
Old 06-19-2012
Mead Rotor
 
Join Date: Aug 2005
Location: Saskatchewan
Posts: 16,371
Thanks: 490
Thanked 2,534 Times in 2,417 Posts
much easier with awk:
Code:
awk '/bbb/ { print ; for(n=0; n<2; n++) { getline ; print } }' inputfile

Sponsored Links
    #3  
Old 06-19-2012
saj saj is offline
Registered User
 
Join Date: Apr 2011
Posts: 29
Thanks: 4
Thanked 0 Times in 0 Posts
Thanks a lot Corona688 ... But is it possible to get a command in sed ..
I tired the below one .. but looks like some issue is there with the command ..

sed -n '/bbb/,+2p' filename
    #4  
Old 06-19-2012
Mead Rotor
 
Join Date: Aug 2005
Location: Saskatchewan
Posts: 16,371
Thanks: 490
Thanked 2,534 Times in 2,417 Posts
Right tool for the right job and all that. Why sed? Is this homework?
Sponsored Links
    #5  
Old 06-19-2012
saj saj is offline
Registered User
 
Join Date: Apr 2011
Posts: 29
Thanks: 4
Thanked 0 Times in 0 Posts
No not home work I am learning sed commands ..
Sponsored Links
    #6  
Old 06-20-2012
jayan_jay's Avatar
Forum Advisor
 
Join Date: Jul 2008
Posts: 831
Thanks: 9
Thanked 185 Times in 176 Posts

Code:
$ sed -n '/bbb/ {p;n;p;n;p;}' infile

Sponsored Links
    #7  
Old 06-20-2012
Registered User
 
Join Date: Mar 2012
Posts: 18
Thanks: 1
Thanked 3 Times in 3 Posts
Try this one

Code:
grep -A2 'bbb' inputfile

Sponsored Links
Closed Thread

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

More UNIX and Linux Forum Topics You Might Find Helpful
Thread Thread Starter Forum Replies Last Post
pattern match and replace another pattern in same line anilcliff Shell Programming and Scripting 7 11-18-2011 01:45 PM
Print Line if next line Match a pattern kittiwas Shell Programming and Scripting 2 10-19-2011 12:10 AM
Perl: Printing Multiple Lines after pattern match Deep9000 Shell Programming and Scripting 5 07-14-2009 09:38 AM
Printing out pattern in line FK_Daemon Shell Programming and Scripting 3 11-23-2007 03:27 PM
sed - Replace Line which contains the Pattern match with a new line kousikan Shell Programming and Scripting 2 03-24-2007 07:24 AM



All times are GMT -4. The time now is 07:16 PM.