首页 > 解决方案 > Show a match (grep) and show one column of the matched line

问题描述

Say I have a following text file (Nmap's .gnmap) and what I want is to show my match and corresponding IP addres. I.e. only show 22/open and 2000/open and also IP of those two ports. I need this result:

10.10.10.1 22/open 2000/open 10.10.10.2 2000/open

To get IPs is simple grep -iE "22/open|2000/open" file, but how do i also display IP? I need following output (exact extra characters does not matter, as long as each line contains IP and port):

Example source file:

Host: 10.10.10.1 () Ports: 22/open/tcp//ssh///, 80/open/tcp//http///, 113/closed/tcp//ident///, 443/open/tcp//https///, 541/open/tcp//uucp-rlogin///, 2000/open/tcp//cisco-sccp///  Ignored State: filtered (4994)
Host: 10.10.10.2 () Ports: 113/closed/tcp//ident///, 2000/open/tcp//cisco-sccp///   Ignored State: filtered (4998)

标签: grep

解决方案


Could you please try following.

awk '
match($0,/[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/){
  ip_found=substr($0,RSTART,RLENGTH)
}
{
  while(match($0,/22\/open|2000\/open/)){
    val=(val?val OFS:"")substr($0,RSTART,RLENGTH)
    $0=substr($0,RSTART+RLENGTH)
  }
  if(ip_found){
    print ip_found,val
  }
  ip_found=val=""
}
' Input_file

Output will be as follows.

10.10.10.1 22/open 2000/open
10.10.10.2 2000/open

推荐阅读