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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

extract lines from a file 1

Status
Not open for further replies.

madra

MIS
Feb 12, 2003
95
GB
I want to search for text in a file, when the text is found display that line and the following two lines (format of the file), then continue searching for the next hit.

eg.
search for 'help'
display the 'help' line
disply the next two lines in the file
continue the search for 'help'

Anyone know how this is done ?

thanks
madra


I only ask stupid questions because I'm thick
 
Can you install the gnu grep for AIX. That includes the -A option allowing grep to print lines after the matched one. Otherwise a web search finds several perl and awk based solutions.

The internet - allowing those who don't know what they're talking about to have their say.
 
This is a slight modification to a post found here that might work without having to download gnu awk:

Code:
awk 'c-->0;$0~s{if(b)for(c=b+1;c>1;c--)print r[(NR-c+1)%b];print;c=a}b{r[NR%b]=$0}' b=0 a=2 s="[b]string to search for[/b]" filename

modify the b= and a= values to how many lines you want to print before and/or how many after

Let us know if this works for you.

Regards,
Chuck
 
Chuck,
nice one

just ran it for the first time, and success

good man

thanks

madra


I only ask stupid questions because I'm thick
 
...and worthy of a star then. madra?

The internet - allowing those who don't know what they're talking about to have their say.
 
I'll give Chuck a star for that if madra is not listening.
 
Code:
cat text | sed -n '/help/{p;n;p;n;p;n;}'


cat text
Code:
this is a help file
just text
more text
nothing
junior
the sun is hot
help me wash my car
my car is dirty
i like my car
just babble
abc
def
apples are good
oranges are better
the sea is blue
the sky is too

# cat text | sed -n '/help/{p;n;p;n;}'
Code:
this is a help file
just text
more text
help me wash my car
my car is dirty
i like my car
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top