awk and shell question

Geoff Clare gwc at root.co.uk
Sat Sep 23 23:25:53 AEST 1989


In article <1989Sep20.210951.10759 at eci386.uucp> clewis at eci386.UUCP (Chris Lewis) writes:
>In article <1163 at ispi.UUCP> jbayer at ispi.UUCP (Jonathan Bayer) writes:
>>
>>HELP!!  I have been pulling my hair out over this seemingly simple
>>problem:

[ awk script deleted ]

>Your problem is how to get parameters into an awk program.  
>
>The other solutions probably work, but I'm posting because of the general
>applicability of the technique I'm going to demonstrate here, not so much 
>the specific example (I normally use sed for picking apart /etc/passwd)
>
>This technique is in some of the AT&T UNIX V3 UNIX documentation.  And 
>appears in many well written awk programs that have been published.  
>I use it *very* extensively (10K+ awk scripts in production code):
>
>a=`awk -F: '$1 == "'$LOGNAME'" { print $5}'`
                                            ^ /etc/passwd missing

I find it much more readable, and less prone to error, to assign the
necessary awk variables on the command line:

a=`awk -F: '$1 == LOGNAME { print $5 }' LOGNAME="$LOGNAME" /etc/passwd`

If the awk program is very long, this also means you can put it
in a file for use with '-f', and still be able to set dynamic
values for use in the program.

The only problem with this method is if you want awk to read stdin.
Most implementations incorrectly only read stdin if there are no
arguments at all, not if there are no file arguments.  However you can
get round this by giving a file name of "-".
-- 
Geoff Clare, UniSoft Limited, Saunderson House, Hayne Street, London EC1A 9HH
gwc at root.co.uk  (Dumb mailers: ...!uunet!root.co.uk!gwc)  Tel: +44-1-315-6600



More information about the Comp.unix.wizards mailing list