1752402 Members
5650 Online
108788 Solutions
New Discussion юеВ

grep in surrounding area

 
SOLVED
Go to solution
Raf_L
Occasional Advisor

grep in surrounding area

Hello Team,

I'm looking for a way of grepping a keyword in a file, but also to find the surrounding area.

Let me give you an example
******************myfile.txt***********
hostname=A
IP-ADDRESS=B
hostname=C
IP-ADDRESS=D
hostname=E
IP-ADDRESS=F
***************************************
So now I'm looking for a way to "grep" the file in such a way that I will be able to "find the IP-ADDRESS of hostname C"

so I could do
grep "hostname=C" myfile.txt + display the next line, but I have no idea in how to do that in an proper way.

Any ideas ?

brgds,


Raf
3 REPLIES 3
Dennis Handly
Acclaimed Contributor
Solution

Re: grep in surrounding area

>grep "hostname=C" myfile.txt + display the next line

GNU grep has -A1 to display the next line.

Otherwise you could use awk:
awk -v search="hostname=C" '
$0 ~ search {
print $0
getline
print $0
} ' myfile.txt
Raf_L
Occasional Advisor

Re: grep in surrounding area

Hello,

the awk example seems to work ! Thx.

Just waiting for maybe new clues, but this is already the best thing I've tested !

Raf
James R. Ferguson
Acclaimed Contributor

Re: grep in surrounding area

Hi Raf:

Thie Perl solution will give both the line before and after the matching one:

# perl -ne 'BEGIN{$token=shift};if (m{$token}) {print $prev,$_;$_=<> and print unless eof};$prev=$_' hostname=C myfile.txt

Regards!

...JRF...