簡體   English   中英

使用awk進行字符串匹配

[英]string match using awk

我有一個制表符分隔的文件,其中包含這樣的行:

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 contains either "add" or "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' 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.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM