Reputation: 45
in a unix shell script I have
filename=myfile
LOG=/dir/log*
j=`awk '/AAAA/ && /BBB/ && /${filename}/ && /CCC/' ${LOG}`
but when the script runs, with set -x I see:
awk /AAA/ && /BBB/ && /${filename}/ && /CCC/ /dir/log1 /dir/log2
How can I escape the ${filename} variable within the awk argument so that it resolves correctly ?
To illustrate what I am trying to do
I have a file called /tmp/S20150814.001 which contains
This line contains AAAA and BBB and CCC and bcd_input_13082015_0800.txt
In my script, if I use
MYLOG=/tmp/S20150814.001
j=`awk '/AAAA/ && /BBB/ && /bcd_input_13082015_0800.txt/ && /CCC/' ${MYLOG}`
if [[ ${#j} -gt 0 ]]
then
and run the script I see
+ + awk /AAAA/ && /BBB/ && /bcd_input_13082015_0800.txt/ && /CCC/ /tmp/S20150814.001
j=This line contains AAAA and BBB and CCC and bcd_input_13082015_0800.txt
+ [[ 71 -gt 0 ]]
but if I change the script to
MYLOG=/tmp/S20150814.001
filename=bcd_input_13082015_0800.txt
j=$(awk -v filename="$filename" '/AAAA/ && /BBB/ && $0==filename && /CCC/' ${MYLOG})
if [[ ${#j} -gt 0 ]]
then
and run it, I get
+ + awk -v filename=bcd_input_13082015_0800.txt /AAAA/ && /BBB/ && $0==filename && /CCC/ /tmp/S20150814.001
j=
+ [[ 0 -gt 0 ]]
Upvotes: 0
Views: 448
Reputation: 45
I got this to work by
j=$(awk -v filename="$filename" '/AAAA/ && /BBB/ && $0 ~ filename && /CCC/' ${MYLOG})
ie a space was needed before and after the "~"
Upvotes: 0
Reputation: 46856
You shouldn't put filenames inside the code of your awk script like that. If you need to pass in a variable, awk has an option for that.
j=$(awk -v filename="$filename" '/AAAA/ && /BBB/ && $0~filename && /CCC/' ${LOG})
Or, since your filename might contain characters interpreted as part of a regular expression, perhaps you really want:
j=$(awk -v filename="$filename" '/AAAA/ && /BBB/ && $0==filename && /CCC/' ${LOG})
See also: https://stackoverflow.com/a/9712555/1072112 for some help on how various types of quotes work.
Upvotes: 5