Path: utzoo!mnetor!uunet!husc6!hao!noao!arizona!rupley From: rupley@arizona.edu (John Rupley) Newsgroups: comp.unix.questions Subject: Re: Expansion of variables in sh scripts Message-ID: <3859@megaron.arizona.edu> Date: 14 Feb 88 21:04:29 GMT References: <1159@valhalla.ee.rochester.edu> Organization: U of Arizona CS Dept, Tucson Lines: 36 Keywords: Forward quote, backword quote, double quote, auuuuuuuuugh! Summary: easy to fix, but there's a better way In article <1159@valhalla.ee.rochester.edu>, badri@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@megaron.arizona.edu (H) 30 Calle Belleza, Tucson AZ 85716 - (602) 325-4533 (O) Dept. Biochemistry, Univ. Arizona, Tucson AZ 85721 - (602) 621-3929