jbt828
October 16, 2009, 8:10am
1
If anyone knows why $cc is ignored in the following awk.
When I use a value it works ok.
cc=`grep -a "ControlID" in.file | cut -c 375-378`
$cc is equal to "XXXX"
does not work:
cat in.file|awk -v cnt=0 -v replace=" " '/$cc/{if (cnt=="0"){sub(/$cc/,replace)};cnt++} {print}' > out.file
works:
cat in.file|awk -v cnt=0 -v replace=" " '/XXXX/{if (cnt=="0"){sub(/XXXX/,replace)};cnt++} {print}' > out.file
Scott
October 16, 2009, 8:51am
2
Hi.
You're using a shell variable inside awk.
awk -v cnt=0 -v replace=" " '/'$cc'/ {if (cnt=="0"){sub(/$cc/,replace)};cnt++} {print}' in.file > out.file
or
awk -v cnt=0 -v cc=$cc -v replace=" " '$0 ~ cc {if (cnt=="0"){sub(/$cc/,replace)};cnt++} {print}' in.file > out.file
You've blocked the shell from expanding $cc with the single quotes:
cat in.file|awk -v cnt=0 -v replace="NEWSTUFF" "/$cc/{if (cnt=="0"){sub(/$cc/,replace)};cnt++} {print}" > out.file
Of course, now you must be careful of any currency signs ($) in your awk(1) script.
jbt828
October 16, 2009, 4:31pm
4
Thank Guys! I'm doing some testing. Looks like it works for the first occurance in the file when the cnt=0, but when I change the... if cnt=="1" then the second does not get change... I'll do more testing.
Scott
October 16, 2009, 6:02pm
5
megacoder:
You've blocked the shell from expanding $cc with the single quotes:
cat in.file|awk -v cnt=0 -v replace="NEWSTUFF" "/$cc/{if (cnt=="0"){sub(/$cc/,replace)};cnt++} {print}" > out.file
Of course, now you must be careful of any currency signs ($) in your awk(1) script.
It's not a great idea to use double quotes to start and end an awk script:
$ echo something | awk "{print $NF}"
something
$ echo something | awk "{ if ($1 == "something") A=$1 }"
awk: { if ( == something) A= }
awk: ^ syntax error
$ echo something | awk "{print "Here is " $NF}"
awk: cmd. line:1: {print Here
awk: cmd. line:1: ^ unexpected newline or end of string
$ echo something | awk "{print 'Here is ' $NF}"
awk: {print 'Here is ' }
awk: ^ invalid char ''' in expression
$ echo something | awk "{print \"Here is \" $NF}"
Here is
Use single quotes and declare the shell variable to awk either as
awk -v cc=$cc '...' file1 file2 ... etc.
or
awk '...' cc=$cc file1 dd=$dd file2 ... etc.
depending on your preference and whether you have a BEGIN clause or not.