Expansion of variables in sh scripts

John Rupley rupley at arizona.edu
Sat Feb 27 06:37:14 AEST 1988



In article <2004 at ho95e.ATT.COM>, wcs at ho95e.ATT.COM (Bill.Stewart) writes:
> 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
           ^ [please note the plural]
> >for a word in the I column and outputs the corresponding entry in
> >the II column.
> 
> For this application, I'd recommend 
> 	: Usage: myname pattern file
> 	egrep "^$1 " $2 | cut -f2 -d" "

The above won't work, as it cuts at the first blank of a possible series
of whitespace characters.  The following fits the specification and can
be adapted to include other types of whitespace, eg, tabs:
        egrep "^$1 " $2 | tr -s " " " " | cut -f2 -d" "

This points up why awk is useful - it has fewer gotchas, of the above
nit-picky kind, and the code is straightforward:
	awk '$1 == patone {print $2}' patone="$1" $2

> Even if you decide to use awk instead of cut to extract the second
> column (and presumably do summaries or other useful work), you'll
> speed the program up significantly by using egrep to reduce the
> amount of data that awk has to process.

Right! But only if the file to be searched is long.  For short files, 
awk, with a single load and no pipes, is faster -- try it! Also, even 
for search of large files, if you prototype in awk, and subsequently, 
if execution time is a bore, recode (even in C (:-), you will probably 
save effort.

> # Bill Stewart, AT&T Bell Labs 2G218, Holmdel NJ 1-201-949-0705 ihnp4!ho95c!wcs

John Rupley
 uucp: ..{ihnp4 | hao!noao}!arizona!rupley!local
 internet: rupley!local at megaron.arizona.edu
 telex: 9103508679(JARJAR)
 (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