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

I want to add word boundaries to this awk command:

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

I tried adding \yleft and right of wordAand wordB, but it did not work in my tests.
I tried this:/\ywordA\y/&&/\ywordB\y/

Thanks everyone!

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

+2
source share
3 answers

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 (for example, on Mac OS X). \ y is a GNU extension for awk.

+3
source
  • GNU awk also supports the agreement \<and \>for the word boundaries.
  • Mac /usr/bin/awk 20070501 [[: <:]] [[: > :]]
  • awk, , awk , :

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

, ,

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

:

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

This might work for you on Mac OS X :

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

But since it will not work on Linux, your best bet is to install GNU awk.

0
source

Source: https://habr.com/ru/post/1693870/


All Articles