bash 仅在字段不为空时打印

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43790965/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 16:07:30  来源:igfitidea点击:

Print only if field is not empty

bashawkgrep

提问by teamg

I have a text file that I want to pull host and IP info from only if the IP exists in column 4. For example:

我有一个文本文件,仅当 IP 存在于第 4 列中时,我才想从中提取主机和 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

In this case I would only want to see Server One and Three as Server Two has no data in the fourth column.

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

回答by Kyle Banerjee

awk '{if () print 
awk 'NF>=4 && ~/^([0-9]{1,3}\.){3}[0-9]{1,3}$/' hostlist.txt
;}' < hostlist.txt

does the trick. It's functionally equivalent to the earlier solution but is simpler since you only check for existence rather than matching a regex.

诀窍。它在功能上等同于早期的解决方案,但更简单,因为您只检查是否存在而不是匹配正则表达式。

回答by RomanPerekhrest

awkapproach:

awk方法:

Server One 255.255.255.255 123.123.123.123
Server Three 255.255.255.255 123.123.123.123

The output:

输出:

$ awk '' hostlists.txt
Server One 255.255.255.255 123.123.123.123
Server Three 255.255.255.255 123.123.123.123


NF>=4- ensures that a record has at least 4 fields

NF>=4- 确保记录至少有 4 个字段

$4~/^([0-9]{1,3}\.){3}[0-9]{1,3}$/- ensures that the 4th field contains IPv4 address (in most simple form. Real IPv4 validation requires an additional conditions)

$4~/^([0-9]{1,3}\.){3}[0-9]{1,3}$/- 确保第 4 个字段包含 IPv4 地址(以最简单的形式。真正的 IPv4 验证需要附加条件)

回答by Benjamin W.

If you can live with lines where field 4 has value 0not being printed, you can simplify to

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

##代码##

This is functionally equivalent to {if ($4) print $0;}, but reduced to just a pattern and using the default action of print $0.

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