AWK question (several answers)

ajs ajs at hpfcla.UUCP
Thu Aug 15 08:47:00 AEST 1985


Re: getting user input into an AWK program

There are several ways I know of to do this, depending on what exactly
you need to accomplish.

1.  Just hardwire a couple of selected values into the awk script:

    In this case, if the script is invoked on the command line (e.g.
    from a shell script), get the shell to embed the value in the script
    argument.  Normally awk scripts are surrounded by '' in this case,
    so all you have to do is concatenate the value:

	    awk 'BEGIN { value = '$value'; ... }'

    Suppose the awk script needs a string value.  No problem, more quotes:

	    awk 'BEGIN { value = "'$value'"; ... }'

    Suppose the value itself, coming from a user, might contain blanks.
    Uh-oh, better be careful, one more set of quotes:

	    awk 'BEGIN { value = "'"$value"'"; ... }'

    This looks arcane, but is interpretable to any halfway-intelligent
    shell user who READS THE MANUAL at least once.  Any other way to do
    the same thing (like writing the script to a file, or preparing
    $value) is necessarily more complicated and error-prone.

2.  Read lines from input along with other data:

    Make clever use of sh(1) parentheses to combine the data.  Here is
    an example which initializes a relational mapping (pairs of values)
    from one file, then applies it to input data from a user:

		sep='===sep==='		# separator for awk.

	{	cat mapping		# slurp up mapping.
		echo $sep
		cat			# read stdin.
	} |	awk '

		(flag == 0) {			# read mappings.
		    if ($0 == "'"$sep"'")	# end of mapping.
			flag = 1;
		    else
			map [$1] = $2;		# save a mapping.
		
		    next;
		}

		{				# apply mappings to input.
		    if (map [$1] > "")	print map [$1];
		    else		print;
		}'
			
3.  Read lines from stdin or files after awk starts up:

    Well, the 6/5/85 version of awk described by AT&T adds a getline()
    function, among other things.  You'll have to wait for it (as will I).
    Meanwhile you can get the manual --

	> Jon Bentley's Programming Pearls column in CACM (June 1985)
	> discussed awk and mentioned awk functions.  He mentions that
	> the programmer's manual "for the revised language (featurism
	> creeps relentlessly)" is available from ATT.
	> 
	> You can get it too for free by writing:
	> 
	> Patricia Solomon
	> AT&T Bell Laboratories
	> 600 Mountain Avenue
	> Murray Hill, NJ   07974
	> 
	> and asking for:
	> 
	> Computing Science Technical Report: #118
	> Awk Programmer's Manual (May 1985)

Alan Silverstein, Hewlett-Packard Fort Collins Systems Division, Colorado
{ihnp4 | hplabs}!hpfcla!ajs, 303-226-3800 x3053, N 40 31'31" W 105 00'43"



More information about the Comp.unix mailing list