You can pass *anything* to awk: even in BEGIN!

John M. Ritter jmr at motown.UUCP
Mon Sep 22 23:24:01 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...]
> [ ... ]				     ^^^^^^^^^^
> What it doesn't tell you is this: [ ... ]
>
>	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

I thought this was beat to death a couple of months ago, and I'd like to
present the method I use as it seems to cover every situation.

This method DOES allow initialization within the BEGIN block, and it is
also as easy to use as $1 in a shell script...

I can't think of anything that has been left out. This is using
System V, r2.0v2 - I'd love to know if this works on other versions
of Unix.
------------------------------------------------------------------------------
"I enjoy working with human beings, and                         John M. Ritter
have stimulating relationships with them."                  Allied-Signal Inc.
                            - HAL 9000                Corporate Tax Department
                      {bellcore,harpo,ihnp4,infopro,princeton,sys1}!motown!jmr
------------------------------------------------------------------------------
# awk script to receive arguments from three places:
#	1) Environment (must be exported)
#	2) Initialized within the awk script
#	3) Entered on the command line
#
# execute the script with something like:
#	script argument_1 argument_2

ARG2=$2				# second command argument: Can be identified
				#	here, or in the BEGIN section.
VAR1=something_here		# single argument
VAR2="something else"		# two words is twice the fun

echo " " |
awk '
BEGIN { TERM = "'$TERM'";	# From Environment
	VAR1 = "'$VAR1'";	# From Above
	VAR2 = "'"$VAR2"'";	# From Above: Note strange quotes!
	ARG1 = "'$1'";		# From command line - direct
	ARG2 = "'$ARG2'";	# From command line but identified above
	ESC = 27;		# define ESCAPE code

	if (TERM == "vt100") 	{ REV_ON  = sprintf("%c[7m", ESC);
				  REV_OFF = sprintf("%c[m", ESC);}
      } # End of BEGIN

{	print "Your terminal is: " REV_ON TERM REV_OFF;
	print "VAR1 = " VAR1;
	print "VAR2 = " VAR2;
	print "Command argument 1: " ARG1;
	print "Command argument 2: " ARG2;
}'



More information about the Comp.unix mailing list