I am trying to test if I can replace a regular expression in 'nawk' with a variable.
Please let me know why it is not working. I am using ksh88i on solaris8
I am trying use this test as a building block to filter active external DNS connections.
Ideally I want to pass variable defined outside nawk as an argument to it.
# Here I am printing only DNS names.
$> echo server1.domain1.domain2.com | nawk '/^[a-z0-9]*\.[a-z0-9]*\.[a-z0-9]*\.[a-z0-9]*/{print}'
server1.domain1.domain2.com
# Here I am trying to pass same pattern as a variable, its not working.
$>echo server1.domain1.domain2.com | nawk -v re='^[a-z0-9]*\.[a-z0-9]*\.[a-z0-9]*\.[a-z0-9]*' '/re/{print}'
below might work with some warnings..
tools> echo server1.domain1.domain2.com | awk -v "re=^[a-z0-9]*\.[a-z0-9]*\.[a-z0-9]*\.[a-z0-9]*" '$0 ~ re{print}'
awk: warning: escape sequence `\.' treated as plain `.'
server1.domain1.domain2.com
Slight modification still:
echo "server1.domain1.domain2.com" | awk -v re='^[a-z0-9]*\\.[a-z0-9]*\\.[a-z0-9]*\\.[a-z0-9]*$' '$0~re{print}''
--
@viyadhar: the back slashes need to be escaped within single quotes otherwise the regex in the string will match anything (the dots will not be interpreted as literal dots).
@kchinnam: you probably need a $-sign at the end as well?
My question is really using 'nawk' I am able to get the first command working, but not the second one with parameter, what am I doing wrong?
$> echo server1.domain1.domain2.com | nawk '/^[a-z0-9]*\.[a-z0-9]*\.[a-z0-9]*\.[a-z0-9]*/ {print}'
server1.domain1.domain2.com
$>echo server1.domain1.domain2.com | nawk -v re='^[a-z0-9]*\.[a-z0-9]*\.[a-z0-9]*\.[a-z0-9]*' '/re/ {print}'
<nothing gets printed>
Within awk you can use a so-called regex constant / regex /{print}
or $0 ~ / regex / {print }
but a regex constant cannot contain a variable.
If you want to use a variable you need to put the regex in a string and use the regex matching operator ~
( $0 ~ " regex "{print}
)
So it becomes -v re='regex' ' .... $0 ~ re {print }
. But this means the backslashes do need to be escaped, because the string needs to be evaluated first before it can be interpreted as a regex, hence the double backslashes in my previous example ( in a string you need to use \\
is you want to print \
).