简体   繁体   中英

How to use regex in awk for this case?

I am doing a scan over networks using nmap.

Results going to be below:

Nmap scan report for 30.142.41.52
Host is up.

PORT     STATE    SERVICE
8080/tcp open http-proxy

Nmap scan report for 51.136.230.94
Host is up.

PORT     STATE    SERVICE
8080/tcp filtered http-proxy

Nmap scan report for 58.188.208.42
Host is up.

PORT     STATE    SERVICE
8080/tcp filtered http-proxy

I just wonder how to use grep or awk, to save only the State "open" results and save it in a text file?

I've tried something like...

awk '{print $5}' | sort -n > IPs

But it saves only the IP, so how to use regex in awk to save IPs with OPEN state?

Thank you in advance, regards. //terrisa

awk '/^Nmap/{ip=$5}; / open /{print ip}' file

or

awk '$1=="Nmap"{ip=$5}; $2=="open"{print ip}' file

Output:

30.142.41.52

With awk you can set the Record Separator (RS) with the string of your choice, same thing for the Field Separator (FS):

awk -F"\n" -v RS='Nmap scan report for ' '$5~/ open /{print $1}'

This way, instead of working line by line, awk works block by block (from each 'Nmap scan report for ' until the next); and the Field Separator is a newline (that means that the first field is the IP and the fifth field is the line 8080/tcp open http-proxy ).

Note that if you use gawk, you can store each IP in an array and use the asort function instead of piping the result to sort .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM