user38257
user38257

Reputation: 11

multiline search in grep

I have made a text file of nmap's output and i was trying to find only those ip whose port are open and when i am using grep i am not getting the desired output only one of the item is i am able to get either ip or the text open

data:

Nmap scan report for xxx.xxx.xxx.83 
Host is up (0.050s latency).
PORT   STATE  SERVICE
80/tcp closed http

Nmap scan report for xxx.xxx.xxx.87
Host is up (0.049s latency).
PORT   STATE    SERVICE
80/tcp filtered http

Nmap scan report for xxx.xxx.xxx.89
Host is up (0.051s latency).
PORT   STATE    SERVICE
80/tcp filtered http

Nmap scan report for xxx.xxx.xxx.90
Host is up (0.050s latency).
PORT   STATE  SERVICE
80/tcp closed http

Nmap scan report for xxx.xxx.xxx.93
Host is up (0.051s latency).
PORT   STATE SERVICE
80/tcp open  http

Nmap scan report for xxx.xxx.xxx.96
Host is up (0.051s latency).
PORT   STATE    SERVICE
80/tcp filtered http

Nmap scan report for xxx.xxx.xxx.100
Host is up (0.054s latency).
PORT   STATE    SERVICE
80/tcp filtered http

Upvotes: 1

Views: 270

Answers (4)

Sylvain Leroux
Sylvain Leroux

Reputation: 51980

What about using awk? This will report the IP address the first time an open port is encountered in the nmap output:

sh$ awk '$3=="report"{ IP = $5 } $2=="open"&&IP { print IP; IP="" }' nmap.out
xxx.xxx.xxx.93

Upvotes: 0

clt60
clt60

Reputation: 63892

After awk and grep perl too:

perl -00 -lanE 'say $_ if m/open/' < file

prints:

Nmap scan report for xxx.xxx.xxx.93
Host is up (0.051s latency).
PORT   STATE SERVICE
80/tcp open  http

or

perl -00 -lanE 'say $F[4] if m/open/' < file

prints

xxx.xxx.xxx.93

Upvotes: 1

Mark Setchell
Mark Setchell

Reputation: 207355

If there are always 4 lines per block and the word open is in the last line, you can do:

grep -B4 open file

and it will show the 4 lines before the word open.

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174696

You could try the below awk command,

$ awk -v RS="" '/ open /{print $5}' file
xxx.xxx.xxx.93

It prints the ip (column no 5) only if the certain block contains the text open

Upvotes: 1

Related Questions