我有一个制表符分隔的文件,其中包含这样的行:
field1 field2 field3 field4 field5 field6
1 abc 2 word:add,word:remove text string
2 xyz 2 word:replace,word:modify msg string
3 lmn 1 word:add msg numeric
4 cncn 2 phone:add,phone: remove msg numeric
5 lmn 2 word:add msg text
我想写一个 awk 程序/oneliner 给我行
field3 ==2
和 field4 包含“add”或“remove”
也就是说应该先过滤掉这些,
1 abc 2 word:add,word:remove text string
2 xyz 2 word:replace,word:modify msg string
4 cncn 2 phone:add,phone:remove msg numeric
5 lmn 2 word:add msg text
在第二步应该已经过滤掉了这些
1 abc 2 word:add,word:remove text string
4 cncn 2 phone:add,phone:remove msg numeric
5 lmn 2 word:add msg text
我可以使用以下方法正确迈出第一步:cat test.tsv | awk -F '\t' '$3 == 2'
如何匹配第二部分的子字符串? 提前致谢
最佳答案
您可以使用 ~
匹配字段:
awk -F '\t' '$3==2 && $4 ~ /add|remove/' filename
会产生想要的结果:
1 abc 2 word:add,word:remove text string
4 cncn 2 phone:add,phone: remove msg numeric
5 lmn 2 word:add msg text
引用手册:
~ !~ Regular expression match, negated match. NOTE: Do not use
a constant regular expression (/foo/) on the left-hand side
of a ~ or !~. Only use one on the right-hand side. The
expression /foo/ ~ exp has the same meaning as (($0 ~
/foo/) ~ exp). This is usually not what was intended.
关于regex - 使用 awk 进行字符串匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23258709/