regex - 使用 awk 进行字符串匹配

标签 regex linux awk substring

我有一个制表符分隔的文件,其中包含这样的行:

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 ==2field4 包含“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/

相关文章:

整行的正则表达式反向匹配

python - 分割字符串上的多个匹配

linux - 在 CentOS 中使用 Nginx 作为 Apache 上 wordpress 的反向代理

regex - 查找并替换为可变文本

c# - 从连接字符串上的金额拼接价格

linux - 如何使用 ARP REQUEST/REPLY 包在 Linux 中测试主机 ip 是否可访问?

.net - 在 32 位操作系统上编译的 .NET 程序可以在单声道下的 64 位 Linux 系统上运行而没有任何问题吗?

linux - 对第二列中所有相同字符串的第一列中的值求和

linux - unix - 文件中每列的最大(长度)

python - 数字的正则表达式匹配并将它们重定向到不同的输出文件