Ok, here's the scoop.
- You don't need to use awk's -v var=var option. You can, and the previous poster was correct in this, but it wouldn't hurt to learn bash's rules for quoting and escaping/interpreting characters.
- Starting with bash and leaving awk out of this for a moment, anything between single quotes will be taken literally by bash: no backslash escapes (backslashes will be taken as simple backslashes), no dollar sign interpretation (dollar signs will be taken as simple dollar signs), and so on.
- For bash, anything between double quotes will be interpreted for backslash escapes and dollar signs.
- If you want a backslash or dollar sign within a double quoted string to be taken literally as though it were in a single quoted string, precede that character with a backslash.
- Moving on to awk, you want to compare the $1 (the first field on each data line as seen by awk with a constant value. That constant value isn't really constant; it's in $i. But you want bash to present it to awk as a constant. If awk is to see this as a constant, it needs to be surrounded by double quotes.
In the following script, the
awk command needs to be
double quoted, because you want
bash to interpret the
$i, substituting the appropriate value (a, b, c, or d). But you want the $1 to appear literally as $1 for
awk, so escape the $ in the $1 to make that happen. To put double quotes within a double quoted string, escape each of those quotes. Also escape the $1, $2, and $3 later in the command, because
awk needs to see those dollar signs exactly as they are, with no interpretation by
bash.
I've preceded the
bash/
awk stuff with a simple demonstration of single and double quoting in bash.
Code:
#!/bin/bash
var="a b c d"
for i in $var
do
echo "$i" '$i' "\$i" '\$i'
done
for i in $var
do
awk "\$1 == \"$i\" {print \$1,\$2,\$3}" <<EOD
a aa aaa
e ee eee
i ii iii
b bb bbb
f ff fff
j jj jjj
c cc ccc
g gg ggg
k kk kkk
d dd ddd
h hh hhh
l ll lll
EOD
echo =====================
done
The output looks like this:
Code:
a $i $i \$i
b $i $i \$i
c $i $i \$i
d $i $i \$i
a aa aaa
=====================
b bb bbb
=====================
c cc ccc
=====================
d dd ddd
=====================
Hope this helps.