awk and shell question

Chris Lewis clewis at eci386.uucp
Thu Sep 21 07:09:51 AEST 1989


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:

>a=" awk -F: '\$1 == \"$LOGNAME\" {
>	user=\$5;
>	print user
>	}'"
>USER=`cat /etc/passwd | $a`

>I get the following error:

Various ugly syntax errors.

Several people have given varyingly ugly solutions using other utilities,
evals and so on.

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}'`

Effectively what you want to do is enclose your script in single quotes,
and surround any parameter you want to get in with single quotes again.
The back-quoted command line is actually composed of *three* separate
strings:

	1) 	'$1 == "'
	2)	$LOGNAME
	3)	'" { print $5}'

Only the second one is actually eval'd, the 1st and 2nd one aren't, the
result is concatenated together then run as a command line.

voila.

T'other nice thing is that you don't go completely crazy trying to escape
all of the shell metacharacters in the non-parameterized part of the awk
program.  Sooo, the awk script still looks pretty normal.  In more 
substantial scripts it makes sense to use awk variables:

a=`awk 'BEGIN {
		var1 = "'$var1'"
		var2 = "'$var2'"
	    ....

Actually, even tho it's kinda ugly, the $variable should also be enclosed
in double quotes, ala:

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

Prevents you from being shot in the head by variables containing spaces
and (most) other shell metacharacters.

Disadvantage: introducing single quotes into the awk script is wierd...
eg:

	a=`awk '{ printf "'"'"'" }'`
-- 
Chris Lewis, R.H. Lathwell & Associates: Elegant Communications Inc.
UUCP: {uunet!mnetor, utcsri!utzoo}!lsuc!eci386!clewis
Phone: (416)-595-5425



More information about the Comp.unix.wizards mailing list