On 4/16/2008 2:13 PM, Bruce Barnett wrote:
> Ed Morton <morton@[EMAIL PROTECTED]
> writes:
>
>
>>Only one problem: the script doesn't work. ... You need to turn off the
quoting
>>when the variable is seen. This can be done by ending the quoting, and
>>restarting it after the variable:
>>
>>#!/bin/sh
>>column=$1
>>awk '{print $'$column'}'
>>----------------------
>>
>>which is the worst possible way to pass the value of a shell
>>variable to an awk program (see
>>http://cfaj.freeshell.org/shell/cus-faq-2.html#24
for the right way).
>
>
> I have always felt that it is essential to understand this particular
> mechanism because it solves many shell programming problems. Your
> suggestion can *only* be used with AWK and cannot be applied to sed,
> grep, bash, etc. I prefer to teach the more versatile approach.
By the way, whether it's awk or sed or whatever, IIRC the right way to do
what
you're attempting in the above script is:
#!/bin/sh
column=$1
awk '{print $'"$column"'}'
i.e. you need to quote your shell variable so you get some protection from
some
of the various possible errors this approach introduces, e.g.:
$ var="hello world"
$ awk 'BEGIN{print "'$var'"}'
awk: BEGIN{print "hello
awk: ^ unterminated string
$ echo "foo bar" | sed 's/.*/'$var'/'
sed: -e expression #1, char 10: unterminated `s' command
$ awk 'BEGIN{print "'"$var"'"}'
hello world
$ echo "foo bar" | sed 's/.*/'"$var"'/'
hello world
but of course even that only goes so far:
$ var="hello
world"
$ awk 'BEGIN{print "'"$var"'"}'
awk: BEGIN{print "hello
awk: ^ unterminated string
$ echo "foo bar" | sed 's/.*/'"$var"'/'
sed: -e expression #1, char 10: unterminated `s' command
$ awk -v var="$var" 'BEGIN{print var}'
hello
world
The sed solution requires escaping the text in the variable.
Regards,
Ed.


|