How to pass /bin/sh parameters into awk scripts

Fred Yankowski fcy at iham1.UUCP
Sat Aug 4 00:06:49 AEST 1984


The awk script presented in the original question about passing
parameters to awk:

	awk "BEGIN{id=$2;}{ \
		printf(\"%8d %s\n\", id++, \$0); \
		}' $1

is missing an escape ('\') before the "\n".  /bin/sh will remove the
single escape when evaluating the double-quoted string before it is
passed to 'awk'.

A trick may be employed to avoid all the ugly quoting needed for the
above example.  The following performs the same function:

	awk "
	BEGIN	{id=$2;} "'
		{ printf ("%8d %s\n", id++, $0); }
	' $1

This trick relies on the fact that /bin/sh treats "xxx"'yyy' as
*one* "word": i.e. the contiguous strings are treated as one.  This
is useful for creating a single string, part of which is evaluated
(within double quotes) and part of which is literal.  In the above,
the awk script through the BEGIN line is evaluated, the rest is
literal.

The 'awk' manual page talks about passing parameters via the command
line, but I've never been able to make it work and the source for
awk does not seem to attempt to obtain such parameters anyhow.  Who knows?


    Fred Yankowski ::: AT&T Bell Laboratories ::: ihnp4!iham1!fcy
			  IH 6B-216  x6902



More information about the Comp.unix.wizards mailing list