仅在字段不为空时打印

tea*_*amg 1 bash awk grep

我有一个文本文件,仅当第4列中存在IP时,我才想从其中提取主机和IP信息。例如:

cat hostlist.txt
Server One 255.255.255.255 123.123.123.123
Server Two 255.255.255.255 
Server Three 255.255.255.255 123.123.123.123
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我只希望看到服务器一和服务器三,因为服务器二在第四列中没有数据。

Kyl*_*jee 5

awk '{if ($4) print $0;}' < hostlist.txt
Run Code Online (Sandbox Code Playgroud)

绝招。它在功能上与早期的解决方案等效,但是更简单,因为您只检查存在性而不匹配正则表达式。

  • 因为`awk`命令是由`condition {actions}`构成的,并且由于默认的动作是print,所以可以将其压缩为`awk'$ 4'hostlist.txt` :) (4认同)

Ben*_* W. 5

如果您可以接受字段 4 的值0未打印的行,则可以简化为

$ awk '$4' hostlists.txt
Server One 255.255.255.255 123.123.123.123
Server Three 255.255.255.255 123.123.123.123
Run Code Online (Sandbox Code Playgroud)

这在功能上等同于{if ($4) print $0;},但简化为一个模式并使用 的默认操作print $0