Hi,
I am trying below code but the word boundaries not seem to be working. What am I doing incorrectly?
echo " ECHO " | awk '{ q="ECHO" ; if ( $0 ~ /\bq\b/) print "HELLO" ; }'
OR
echo " ECHO " | awk '{ q="ECHO" ; if ( $0 ~ /\b'$q'\b/) print "HELLO" ; }'
Or
echo " ECHO " | awk '{ q="ECHO" ; if ( $0 ~ /\<'$q'\>/) print "HELLO" ; }'
echo " ECHO " | awk '{ q="ECHO" ; if ( $0 ~ q) print "HELLO" ; }'
HELLO
That's not what I was looking for. Your example wouldd match the string present anywhere. Hence wanted to check the word boundaries
Try:
awk '/(^|[[:blank:]])ECHO([[:blank:]]|$)/{print "HELLO"}'
If you want to try this on a Solaris/SunOS system, change awk
to /usr/xpg4/bin/awk
, /usr/xpg6/bin/awk
, or nawk
.
Seems like variables cannot be used as part of a regex enclosed in slashes. Apart from that, \b
is a escape sequence for backspace
...
Try this:
$ echo " ECHO" | awk '{ q="ECHO" ; if ( $0 ~ " " q " " ) print "HELLO" ; }'
$ echo "ECHO " | awk '{ q="ECHO" ; if ( $0 ~ " " q " " ) print "HELLO" ; }'
$ echo " ECHO " | awk '{ q="ECHO" ; if ( $0 ~ " " q " " ) print "HELLO" ; }'
HELLO
$ echo " ECHO " | awk '{ q="ECHO" ; if ( $0 ~ " " q " " ) print "HELLO" ; }'
HELLO
$ echo " ECHO " | awk '{ q="ECHO" ; if ( $0 == " " q " " ) print "HELLO" ; }'
$
Hope this helps.
Don Cragun, I was working with variables and wanted to check the whole words only. Do you know how to do it?
Junior - helper , That's exactly what I was struggling with.
Apart from concatenation and checking the begining and end of strings, isnt there any other way of doing this?
awk -v word="$variable" '$0 ~ "(^|[[:blank:]])" word "([[:blank:]]|$)"{print "found"}'
will print found
if the expansion of $variable
(treated as an extended regular expression) appears at the start of a line or follows a space or tab AND a space of tab follows it or it appears at the end of a line.