How to read shell variables in awk
I just wrote this in another thread, then realised it was not what the OP was asking <Blush> Might come in useful to someone...
Here's some basic information about getting command line parameters to a shell script into awk. You do it by manipulating quotes. Here's an example: Quote:
Look: Code:
$ cat xxx Code:
$ cat xxx |
You can save quoting effort with awk's -v option:
Code:
awk -va="$1" -vb="$2" -vc="$3" 'BEGIN { print a, b, c; }' |
Well maybe a little overkill, but here is another alternative:
Code:
#!/bin/bash Code:
./script.sh one two three |
Ahh! ARGC and ARGV are the arguments to awk itself, and you have made the arguments to the shell script available by including $@ as the first argument.
It is elegant, and does not suffer the absolute dependency on getting the quotes right that my solution does. Getting those quotes right is not too bad on a one-liner, but can be a real headache in anything longer. Nice. Thanks. |
I also should point out that this is not quite safe as it stands:
Code:
awk 'BEGIN { a="'$1'"; b="'$2'"; c="'$3'"; print a, b, c; }' Code:
awk 'BEGIN { a="'"$1"'"; b="'"$2"'"; c="'"$3"'"; print a, b, c; }' Code:
awk "BEGIN { a=\"$1\"; b=\"$2\"; c=\"$3\"; print a, b, c; }" Speaking of which, another option is the little-known feature in awk that lets you set up variables as arguments after the expression, and before the filename(s) that they apply to. Code:
awk '{ print a, b, c }' a="$1" b="$2" c="$3" inputfile |
Quote:
I think I should have a signature: ten years out of date and relearning! Because it's true, and I only realised the danger of not using the first set of " when I saw the syntax errors. Quote:
|
All times are GMT -5. The time now is 12:20 AM. |