Ankur Agarwal
Ankur Agarwal

Reputation: 24768

command substitution in bash with awk

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

Upvotes: 3

Views: 6923

Answers (2)

Diego Torres Milano
Diego Torres Milano

Reputation: 69248

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

Upvotes: 5

Dennis Williamson
Dennis Williamson

Reputation: 360153

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.

Upvotes: 11

Related Questions