有条件地返回下一行

有条件地返回下一行

我正在尝试返回具有 Windows 操作系统的计算机的 IP 地址列表(用于我的安全课程)。输出是这种格式

Nmap scan report for 192.168.xx.xxx
Host is up (0.066s latency).
PORT    STATE SERVICE
139/tcp open  netbios-ssn
445/tcp open  microsoft-ds
MAC Address:

Host script results:
| smb-os-discovery: 
|   OS: Windows Server (R) 2008 Standard 6001 Service Pack 1 (Windows Server (R) 2008 Standard 6.0)
|   OS CPE: cpe:/o:microsoft:windows_server_2008::sp1
|   Computer name: 
|   NetBIOS computer name: 
|   Workgroup: WORKGROUP
|_  System time: 2015-12-22T17:01:33-08:00

我能够使用以下方法将值转换为更好的格式grep "for\|Windows"

Nmap scan report for 192.168.xx.xx1
|   OS: Windows XP (Windows 2000 LAN Manager)
Nmap scan report for 192.168.xx.xx5
|   OS: Windows 2000 (Windows 2000 LAN Manager)
Nmap scan report for 192.168.xx.xx8
Nmap scan report for 192.168.xx.x15

如果下一行包含“|”,我现在尝试获取上一行的值(grep)性格,但我不知道如何。我尝试过使用tr "|" "\b"但没有用

输入(存储在文本文件中)

Line 1
|   Line2
Line 3
|   Line 4
Line 5
|   Line 6
Line 7
Line 8
Line 9
|   Line 10
Line 11

所需输出

Line 1
Line 3
Line 5
Line 9

答案1

您可以不使用,grep例如,sed您可以保存带有 IP 的行以保存缓冲区,并仅当操作系统为 Windows 时将其复制到模式空间(删除所有其他行):

... | sed '/^Nmap scan report for/h;/^|[[:blank:]]*OS: Windows/!d;g'

或者,以类似的方式,使用awk,这次仅打印 IP 而不是整行:

... | awk '/^Nmap scan report for/{t=$5};/^\|[[:blank:]]*OS: Windows/{print t}'

答案2

sed -e'$!N;/\n|/P;D' \
<<""
Line 1
|   Line2
Line 3
|   Line 4
Line 5
|   Line 6
Line 7
Line 8
Line 9
|   Line 10
Line 11

Line 1
Line 3
Line 5
Line 9

如果再深入的话...

sed -e'/^ *|/!{$!N;/\n|/P;}' -eD \
<<""
Line 1
|   Line2
|   Line 3
|___|   Line 4
    |   Line 5
    |___Line 6
Line 7
Line 8
Line 9
|   Line 10
Line 11

Line 1
Line 9

您可以删除grepw/...

sed -ne'/^Nmap.* /!{/^|.*: Win.*(W/!d;}' \
    -e's///;/)/H;x;s/\n/: (W/p' \
<<""
Nmap scan report for 192.168.xx.xxx
Host is ...
bla... and more ...
and bla and so on...
#
Host script results:
| smb-os-discovery:
|   OS: not windows Server (R) ... !(Windows Server (R) 2008 Standard 6.0)
|   OS CPE: cpe:/o:microsoft:windows_server_2008::sp1
|   Comp ... some words ...
|   Net... more words ...
|   Work... words again ...
|_  Sys...
#
Nmap scan report for 192.168.xx.xxx
Host is ...
MAC Address:
#
Host script results:
| smb-os-discovery:
|   OS: Windows Server (R) 2008 Standard 6001 Service Pack 1 (Windows Server (R) 2008 Standard 6.0)
|_  System time: 2015-12-22T17:01:33-08:00

192.168.xx.xxx: (Windows Server (R) 2008 Standard 6.0)

相关内容