2
votes

Why does this work:

This

var=hello
myvar=`echo hello hi | awk "{ if (\\\$1 == \"$var\" ) print \\\$2; }"`
echo $myvar

gives

hi

But this does not?

This

var=hello
echo hello hi | awk "{ if (\\\$1 == \"$var\" ) print \\\$2; }"

gives

awk: cmd. line:1: Unexpected token

I am using

GNU bash, version 4.1.5(1)-release (i486-pc-linux-gnu)

on

Linux 2.6.32-34-generic-pae #77-Ubuntu SMP Tue Sep 13 21:16:18 UTC 2011 i686 GNU/Linux

2
You can try both the code. You will see and error for second one. - Ankur Agarwal
That's not the way SO works. A well-formed question includes an explanation of your objective and the results that do not meet your expectations. People may well try your code, but it is up to you to explain your question completely. - Jim Garrison
Ok I edited my question and added the outputs I am getting. - Ankur Agarwal
I get a different error: backslash not last character on line. Try set -x before and set +x after your commands to see a trace of how things work such as variable substitution and backslash evaluation. - Dennis Williamson
@DennisWilliamson Ok will try that. Thanks. - Ankur Agarwal

2 Answers

10
votes

The correct way to pass shell variables into an AWK program is to use AWK's variable passing feature instead of trying to embed the shell variable. And by using single quotes, you won't have to do a bunch of unnecessary escaping.

echo "hello hi" | awk -v var="$var" '{ if ($1 == var ) print $2; }'

Also, you should use $() instead of backticks.

5
votes

If your awk is like mine, it will tell you where it fails:

var=hello
echo hello hi | awk "{ if (\\\$1 == \"$var\" ) print \\\$2; }"

awk: syntax error at source line 1
 context is
    { if >>>  (\ <<< $1 == "hello" ) print \$2; }
awk: illegal statement at source line 1

furthermore, if you replace awk by echo you'll see clearly why it fails

echo hello hi | echo "{ if (\\\$1 == \"$var\" ) print \\\$2; }"
{ if (\$1 == "hello" ) print \$2; }

there are extra '\' (backslashes) in the resulting command. This is because you removed the backquotes. So the solutions is to remove a pair of \'s

echo hello hi | awk "{ if (\$1 == \"$var\" ) print \$2; }"
hi