**********NB -i have read previous posts that look like duplicates but I cannot get this to work, Id really appreciate an explicit answer ********** I know this is a duplicate but I have read the previous posts and I still cant get this to work. sorry.
I'm working in bash trying to match a pattern that is stored in a variable using awk
In this example the string I want to match is xxx and I am storing it in the variable pattern. Imagine in the file $file there is a line that reads xxx yyy
Then if I enter the pattern string explicitly
awk '/xxx/{print $0}' $file
the output is xxx yyy (which is what I want, its printed out the line containing xxx)
but if I pass the pattern to be matched via a variable then there is no match
pattern="xxx"
awk -v pat="$pattern" '/pat/{print $0}' $file
no output
I checked the variable was getting passed to awk with
awk -v pat="$pattern" 'BEGIN {print pat}'
output: xxx as I was hoping.
Sorry, I guess this is easy but I'd really appreciate an answer. thanks
$0 ~ pat
rather than/pat/
as explained here Pass shell variable as a /pattern/ to awk – steeldriver Feb 07 '19 at 19:02/pat/
was allowed to mean "match the contents of variablepat
", then it would no longer be possible to match the regular expressionp
a
t
- whereas$0 ~ pat
versus$0 ~ "pat"
is unambiguous) – steeldriver Feb 07 '19 at 19:48