Awk 部分字符串匹配(如果列/单词部分匹配)

我的假文件是这样的:

C1    C2    C3
1     a     snow
2     b     snowman
snow     c     sowman

如果在 $3中有字符串 snow,我想得到行。我可以这样做:

awk '($3=="snow" || $3=="snowman") {print}' dummy_file

但应该有更简单的方法。

284333 次浏览

Maybe this will help

http://www.math.utah.edu/docs/info/gawk_5.html

awk '$3 ~ /snow|snowman/' dummy_file
awk '$3 ~ /snow/ { print }' dummy_file

Print lines where the third field is either snow or snowman only:

awk '$3~/^snow(man)?$/' file

GNU sed

sed '/\s*\(\S\+\s\+\)\{2\}\bsnow\(man\)\?\b/!d' file

Input:

C1    C2    C3
1     a     snow
2     b     snowman
snow     c     sowman
snow     snow     snowmanx

..output:

1     a     snow
2     b     snowman

Also possible by looking for substring with index() function:

awk '(index($3, "snow") != 0) {print}' dummy_file

Shorter version:

awk 'index($3, "snow")' dummy_file