要求awk打印包含几个单词的特定单词



例如,我有一个句子,单词以!在日志文件

0 1 ! abs tHfih(t) qcds bbc(u)
使用下面的代码,我可以找到 这行
  awk '
  /[Tt][Hh][Ff]/ { if ($3 ~ /!/) {print "a"; exit 0}}

我如何告诉awk打印整行和包含"tHfih(t)"的完整单词?

打印行

awk '
/[Tt][Hh][Ff]/ { if ($3 ~ /!/) {print "the line containing the match"; exit 0}}

打印单词

awk '
    /[Tt][Hh][Ff]/ { if ($3 ~ /!/) {print "the word containing the match"; exit 0}}

这可能更简单

awk 'tolower($0) ~ /thf/ && $3=="!"'

更新如果不知道搜索字段的位置,则使用

。您可以扫描所有字段以查找匹配项。例如,对于第三个位置有!的行,打印包含thf的行号和单词,不区分大小写

awk '$3=="!"{for(i=1;i<=NF;i++) if(tolower($i)~/thf/) print NR, $i}'
更新2

如果你想切换匹配的单词和行

awk -vw=1 '$3=="!"{for(i=1;i<=NF;i++) if(tolower($i)~/thf/) print w?$i:$0}' file

设置w=0为整行打印,为1为字打印。请注意,这假设该行中只有一个匹配项,否则它将打印所有匹配项(并且在行模式下有那么多行)。

最新更新