Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to print one line before and one line after certain pattern?

Status
Not open for further replies.

whatisthis987

IS-IT--Management
Apr 24, 2007
34
US
Hi guys,
I would like to print the line before and the line after "JohnDoe" is found. For example,

===Input text file===
line1
line2
JohnDoe blah blah blah
line4
line5

===Desired output file===
line2
line4

Can someone suggest a good way of doing this?
 
If you have a suitable version of grep then
Code:
grep -A 1 -B 1 JohnDoe InputFile | grep -v JohnDoe


On the internet no one knows you're a dog

Columb Healy
 

On Linux:

man grep, look at the -A and -B options.
[3eyes]

----------------------------------------------------------------------------
The person who says it can't be done should not interrupt the person doing it. -- Chinese proverb
 
Thank you guys. I never knew the usage of -A and -B. This is perfect.
 
Another way:
awk '/JohnDoe/{print x;getline;print}{x=$0}' /path/to/input

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
Or grep -C1 is equivalent to -A1 and -B1. You only need to specify before and after separately if they are different.

Annihilannic.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top