Expansion of variables in sh scripts

John Rupley rupley at arizona.edu
Mon Feb 15 07:04:29 AEST 1988



In article <1159 at valhalla.ee.rochester.edu>, badri at valhalla.ee.rochester.edu (Badri Lokanathan) writes:
> Given a 2 column file of data in two columns, the columns separated by
> blanks. A script is desired which, among other things, searches for a
> word in the I column and outputs the corresponding entry in the II column.
> There are several ways of doing this; I want to know why the following
> inconsistency took place (I tried it on BSD4.3):
> #!/bin/sh
> word=$1
> result=`awk "/^${word}/{print \$2}" datafile`
> echo $result
> # This outputs the entire line, rather than the entry in the II column.
> awk "/^${word}/{print \$2}" datafile
> # This outputs only the entry in the II column, as expected.

Unless you escape the escape:
	result=`awk "/^${word}/{print \\$2}" datafile`
                                   >> ^ <<
the shell substitutes a null string for $2, and print by default
sends out the full line.  To watch what happens, run under "sh -x".

But you perhaps should avoid shell substitution inside an awk program.
The following does what I think you want to do, more simply and
less ambiguously:
#!/bin/sh
result=`awk '$1 == word {print $2}' word=$1 datafile`
echo $result
awk '$1 == word {print $2}' word=$1 datafile


John Rupley
 uucp: ..{ihnp4 | hao!noao}!arizona!rupley!local
 internet: rupley!local at megaron.arizona.edu
 (H) 30 Calle Belleza, Tucson AZ 85716 - (602) 325-4533
 (O) Dept. Biochemistry, Univ. Arizona, Tucson AZ 85721 - (602) 621-3929



More information about the Comp.unix.questions mailing list