6

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

4 Answers 4

7

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\>/'
4
  • This is also available in BusyBox awk, even if built without glibc. It isn't available in nawk.
    – dubiousjim
    Apr 19, 2012 at 11:39
  • This won't work if the word is at the beginning of end of the line.
    – Barmar
    Apr 17, 2021 at 15:25
  • Fixed it ...... Apr 18, 2021 at 14:13
  • 1
    \< and \> are gawk extensions. With POSIXLY_CORRECT=yes, gawk reports warning: regexp escape sequence `\<' is not a known regexp operator
    – Tekno
    Mar 19, 2023 at 15:40
6

Use \y for word boundary, e.g.

awk '/\yABC\y/'

See https://www.gnu.org/software/gawk/manual/html_node/GNU-Regexp-Operators.html for more details.

1
  • 2
    That link is for gawk. I'm not sure if \y works with awk. Mar 29, 2022 at 15:06
2

Figured it out - was having problems due to a typo

awk '/[^[:alpha:]]ABC[^[:alpha:]]/'
1
  • 4
    This will fail if ABC begins or ends the line.
    – dubiousjim
    Apr 19, 2012 at 11:40
0

Try this:

awk '/( |\t|^|[^a-zA-Z0-9]+)ABC( |\t|$|[^a-zA-Z0-9]+)/' filename

Here: ( |\t|^|[^a-zA-Z0-9]+) means it can only have space/tab/non-alphanumeric character in before ABC or it is the beginning of the line.

Again,( |\t|$|[^a-zA-Z0-9]+) means it can only have space/tab/non-alphanumeric character in after ABC or it is the end of the line.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .