passing command line arguments to awk

David P Huelsbeck dph at lanl.ARPA
Mon Sep 22 15:41:33 AEST 1986


It's not as easy as using a $1 in a shell script but you can define the value
of variables on the command line. This feature is not really documented. 
_The_UNIX_System_User's_Manual_ from AT&T comes the closest. It gives the
SYNOPSIS as this:
	awk [-Fc] [-f progfile] ['program'] [parameters] [file...]
					     ^^^^^^^^^^

It doesn't give any more information about it. However at the end of the
examples it gives this:

>	Print file, filling in page number starting at 5:
>	
>		/Page/ { $2 = n++; } 
>		    { print }
>
>	command line:
>
>		awk -f program n=5 input

Disregarding the fact that this program won't work it does give the general
idea. What it doesn't tell you is this:

	1) You may pass as many <parameters> as you wish provided
	   that the appear between the <program> or -f <progfile>
	   and the firist <file> name.

	2) Each <parameter> assignment must be a single argument.
	   This means no spaces. ( <parameter>=<value> )

	3) Value can as usual be a string or a number. String values
	   however must be enclosed in qoutes WHEN AWK SEE THEM. This
	   means that the double-qoutes must be protected from the shell.
	   (awk -f program stringp=\"avalue\" yourfile)

	4) Environmet variables may be passed this way.
	   (awk -f program dir=\"`pwd`\" file1 file2)

	5) This information is not available within the BEGIN block.
	   It will only become available after the first record has
	   been read and parsed. Therefore if the input is empty it
	   will not be available within the END block either.	

	dph at lanl.arpa

PS: The reason why the program example from the AT&T doc's won't work is
    that "print" is only the default action. Once you do something else
    that something else replaces "print" as the action for that record.
    In 4.2 adding a "print" to the first action still won't make it work
    because assignments to fields other than $0 don't effect $0. This
    bug is fixed in 4.3 and the SysV that I've seen.



More information about the Comp.unix mailing list