Xicheng Jia wrote:
> AL wrote:
>
>>Why in the following code?
>>
>>varA=2;
>>
>>strA="`cat /root/mytempdir/wordlist.txt | awk '{print $ 2}'`"
>>strB="`cat /root/mytempdir/wordlist.txt | awk '{print $ $varA}'`"
>>
>>strA contains the second word of line 1
>>and strB contains all line 1
>>???
>
>
> shell variables within single-quotes are not interpolated.
Right, so to awk "$var" is trying to use an awk (NOT shell) variable
varA to access a positional parameter. Since varA is an unitialised awk
variable, it gets initialised on first use to the value zero, to $varA
is the same as $0 which is the whole input record.
try
> enclosing the awk statements with double quotes.
>
> strB=`cat /root/mytempdir/wordlist.txt | awk "{print $ $varA}"`
No, don't do that as you'd leave yourself open to obscure failures if
your variable isn't set as expected.
Instead set an awk variable based on the value of the shell variable, e.g.:
awk -v varA="$varA" '{print $varA}'
See question 24 in the FAQ,
http://home.comcast.net/~j.p.h/cus-faq-2.html#24, for more details.
Ed