How to use word boundaries in awk without using match() function?

前端 未结 3 1883
太阳男子
太阳男子 2021-01-14 17:42

I want to add word boundaries to this awk command:

awk \'{$0=tolower($0)};/wordA/&&/wordB/ { print FILENAME \":\" $0; }\' myfile.txt
3条回答
  •  时光取名叫无心
    2021-01-14 18:17

    1. GNU awk also supports the \< and \> conventions for word boundaries.
    2. On a Mac, /usr/bin/awk version 20070501 does not support [[:<:]] or [[:>:]]
    3. If you're stuck with a recalcitrant awk, then since awk is normally splitting lines into tokens anyway, it might make sense to use:

      function word(s, i) { for (i=1;i<=NF;i++) {if ($i ~ "^" s "$") {return i}}; return 0; }

    So, for example, instead of writing

    /\<[abc]\>/ { print "matched"; }
    

    you could just as easily write:

    word("[abc]") { print "matched"; }
    

提交回复
热议问题