Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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
share|improve this question
add comment

2 Answers

up vote 1 down vote accepted

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\>'
share|improve this answer
    
Thanks, it works faster too - awk '/\<ABC\>' :) –  bryan Oct 21 '11 at 18:11
    
This is also available in BusyBox awk, even if built without glibc. It isn't available in nawk. –  dubiousjim Apr 19 '12 at 11:39
add comment

Figured it out - was having problems due to a typo

awk '/[^[:alpha:]]ABC[^[:alpha:]]/'
share|improve this answer
    
This will fail if ABC begins or ends the line. –  dubiousjim Apr 19 '12 at 11:40
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.