I recall reading somewhere that when you use a variable in a test, the contents of it are treated as a regex, meaning you should store the entire pattern in the variable and leave the /../ brackets off. I can't locate any clear statement for it in the
gawk manual, but it does appear to be true in testing:
Code:
$ x=78
$ awk -v y="^$x" '$0 ~ y { print }' file.txt
78 foo
$ awk -v y="^$x" 'match( $0 , y ) { print }' file.txt
78 foo
Note though that variables can't be used alone as matching patterns, you have to use a full syntax expression of some kind. This fails to match anything:
Code:
$ awk -v y="^$x" 'y { print }' file.txt
Edit: When using
\y and similar operators in these patterns, you'll have an added problem of the shell condensing backslashes. You need to use three backslashes inside double quotes to ensure that one will remain in the final regex.
Code:
$ awk -v y="\\\y$x\\\y" '$0 ~ y {print}' file.txt
78 foo
100 foo 78
50 foo 78 bar
Edit2: I just noticed the comment mentioning using mawk. Unfortunately it appears that mawk doesn't support the
\y flag. It looks ugly, but how about a regex that tests for the value if at the beginning or end, or if surrounded by spaces? This works with mawk on my machine:
Code:
$ mawk -v y="(^$x|$x$|[ \t]$x[ \t])" '$0 ~ y { print }' file.txt
78 foo
100 foo 78
50 foo 78 bar