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

有些话、适合烂在心里 提交于 2019-12-01 05:56:16

问题


I want to add word boundaries to this awk command:

awk '{$0=tolower($0)};/wordA/&&/wordB/ { print FILENAME ":" $0; }' myfile.txt

I tried adding \y at left and right of wordA and wordB but it didn't work in my tests.
I tried this: /\ywordA\y/&&/\ywordB\y/

Thanks all!

(ps: I'm new to awk so I was trying to avoid the match() function.)


回答1:


You want to use gawk instead of awk:

gawk '{$0=tolower($0)};/\ywordA\y/&&/\ywordB\y/ { print FILENAME ":" $0; }' myfile.txt

will do what you want, if your system has gawk (e.g. on Mac OS X). \y is a GNU extension to awk.




回答2:


  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"; }



回答3:


This might work for you on Mac OS X:

awk '{$0=tolower($0)};/[[:<:]]wordA[[:>:]]/&&/[[:<:]]wordB[[:>:]]/ { print FILENAME ":" $0; }' myfile.txt

But as it won't work on linux you're best off installing GNU awk.



来源:https://stackoverflow.com/questions/9676846/how-to-use-word-boundaries-in-awk-without-using-match-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!