On 4/22/2015 9:17 AM, Dave Farrance wrote:
> Hongyi Zhao <
hongy...@gmail.com> wrote:
>
>> But, all of the above methods seems cumbersome. Could you please give me
>> some more graceful methods for awk to invoke the shell variables?
>
> I don't know what the various rules and downsides are because I'm not
> very familiar with awk, but these seem to work in bash, and Ed would
> probably disapprove of all of them:
Correct but you're actually just showing 1 way not multiple.
>
> $ x=10.0 y=2.5 z=3.0
> $ echo $x $y $z | awk '{print $1 * $2 / $3}'
> 8.33333
I assume the above is just showing the expected result as it's not suggesting
anything about how to use shell var values in awk.
> $ awk "BEGIN {print $x*$y/$z}"
> 8.33333
> $ awk "BEGIN {a=$x*$y/$z; print \"Result: \" a}"
> Result: 8.33333
The above are identical wrt expanding shell vars to become part of the body of
an awk script before it is executed.
Notice you now need to escape double quotes and you'd also need to escape $s for
referencing fields so what should be a simple:
echo 7 | awk -v x="$x" '{y=1; print "Result:", $y * x}'
now needs to be cluttered up with escapes and you have to wonder when you come
across something like this what the heck it all means (e.g. why do the variables
y and x both have $s in front of them but one of them has an escape in front of
that):
echo 7 | awk "{y=1; print \"Result:\", \$y * $x}"
Also note that if x contained an undesirable character then you'd get bizarre
errors or other undesirable behavior from the 2nd one but completely reasonable
behavior from the first. e.g. if x was unset:
$ echo 7 | awk -v x="$x" '{y=1; print "Result:", $y * x}'
Result: 0
$ echo 7 | awk "{y=1; print \"Result:\", \$y * $x}"
awk: cmd. line:1: {y=1; print "Result:", $y * }
awk: cmd. line:1: ^ syntax error
Rhetorical questions: Why is that a syntax error? The syntax LOOKS fine, right?
You can use additional quoting around the shell vars to make awk less sensitive
to their contents but you still end up needing to escape quotes and
field-reference $ signs and it's all pointlessly complicated, obfuscating and
error-prone so just don't do it.
Ed.