Awk match whole word

awkshell-script

I want to use awk to match whole words from text file. Including words bounded by non alphanumeric characters.

For example –

string to search for – ABC

Source file –

HHHABCCCCH
HHH ABC
HH(ABC)ASDAASD
HH,ABC-ASASDASD

Result –

HHH ABC
HH(ABC)ASDAASD
HH,ABC-ASASDASD

Best Answer

  • If you want to pass "ABC" as a variable instead of hardcoding it, use the matching operator:

    awk -v word=ABC '$0 ~ "[^[:alpha:]]" word "[^[:alpha:]]"'
    

    With gawk (other awks too?) you can use \< and \> to denote word boundaries, where a word is a sequence of letters, digits and underscore (I believe), so this will work for your example:

    awk '/\<ABC\>/'
    
  • Related Question