Remove a line surrounded by blank lines

2019-08-28 17:53发布

Basically, I have output from nmap, which gives me an IP and then a list of open ports underneath that, followed by a blank line. I have filtered out the ports that I don't want anymore (grep -v http, for example), but I can't figure out how to remove the IP addesses that have no following ports.

Is there a way to do this with sed?

Sample data:

Nmap scan report for 1.1.1.1
3389/tcp  open  ms-term-serv
5357/tcp  open  unknown
5432/tcp  open  postgresql
8080/tcp  open  http-proxy
49152/tcp open  unknown
49153/tcp open  unknown
49154/tcp open  unknown
49155/tcp open  unknown

Nmap scan report for 2.2.2.2

Nmap scan report for 3.3.3.3
80/tcp    open  http
443/tcp   open  https
6646/tcp  open  unknown
8000/tcp  open  http-alt
49152/tcp open  unknown
49153/tcp open  unknown
49154/tcp open  unknown
49156/tcp open  unknown
49157/tcp open  unknown

标签: linux sed awk
3条回答
甜甜的少女心
2楼-- · 2019-08-28 18:18

It's pretty easy in sed:

sed '$!N;/\n$/d' filename

Or if you want to alter the file in place:

sed -i '' '$!N;/\n$/d' filename
查看更多
成全新的幸福
3楼-- · 2019-08-28 18:19

With awk you can simply do awk '$2' ORS='\n\n' FS='\n' RS= file:

$ awk '$2' ORS='\n\n' FS='\n' RS= file
Nmap scan report for 1.1.1.1
3389/tcp  open  ms-term-serv
5357/tcp  open  unknown
5432/tcp  open  postgresql
8080/tcp  open  http-proxy
49152/tcp open  unknown
49153/tcp open  unknown
49154/tcp open  unknown
49155/tcp open  unknown

Nmap scan report for 3.3.3.3
80/tcp    open  http
443/tcp   open  https
6646/tcp  open  unknown
8000/tcp  open  http-alt
49152/tcp open  unknown
49153/tcp open  unknown
49154/tcp open  unknown
49156/tcp open  unknown
49157/tcp open  unknown

If the extra newline added to the end of file in previous script is a problem then use this alternative:

awk '/^Nmap/{h=$0;i=NR;next}NR==i+1{if($0){print h;p=1}else p=0}p' file
查看更多
在下西门庆
4楼-- · 2019-08-28 18:19

the following awk code segment worked for me for the fictitious file I created as such:

22.22.22.22
dflkhhdfjhdk
tslkdkffhdskjgh

33.33.33.33
tddfgkghdfkj

44.44.44.44

55.55.55.55
ghdkjghdkfjhjdfhg
iuryweiu
kjwhkjfh

66.66.66.66

77.77.77.77
cxlvbclbnc

and run this thru the following awk program:

awk '/[0-9][0-9].[0-9][0-9].[0-9][0-9].[0-9][0-9]/ { K=$0; next }
K { if(length) print K "\n" $0; K=""; next }
1
END { if(K) print K }' infile > outfile

the contents of outfile afterwards are as follows:

22.22.22.22
dflkhhdfjhdk
tslkdkffhdskjgh

33.33.33.33
tddfgkghdfkj

55.55.55.55
ghdkjghdkfjhjdfhg
iuryweiu
kjwhkjfh

77.77.77.77
cxlvbclbnc

The regex I used to match the IP address needs to be modified to match your particular case of course but I think you've already covered it.

Hope this helps. I know it is not sed but close enough I suppose.

查看更多
登录 后发表回答