Re^2: awk and shell question

Andy Behrens andyb at coat.com
Thu Sep 28 03:35:14 AEST 1989


In article <488 at diab.se> gs at diab.se (Greger Sernemar) writes:
> Here is a solution to get parameters into an awk program:
> 
> a="`awk -F: '$1 == NAME {
>        user=$5;
>        print user
>        }' NAME=$LOGNAME - `"
> 
> The last dash (-) closes standard input i.e enables other program to
> pipe to the awk script. I was forced to either supply a file name or
> a dash to be able to set the awk variable.
> I'm not sure if this is a bug in the version of awk I'm using or not.

I'm not sure whether it's a bug or a feature, but it exists on all
versions of awk that I've ever seen.

Variable is not available for use within the script until after the
first record has been read and parsed, but it is available as soon as
that has occurred so that it may be used before any other processing
begins.  It does not exist at the time the BEGIN block is executed, and
if there was no input it will not exist in the END block (if any).

The variable assignment is not made until the filename is encountered in
the argument list, but (feature!) you can reassign values between files. 
For example:


	#!/bin/sh 
	#	Display user names and their default groups
	
	sort /etc/passwd |
	awk -F: 'file=="G" {
		    groupname[$3] = $1
		 }
		 file=="P" {
		    printf "%-12s%s\n", $1, groupname[$4]
		 }' file=G /etc/group file=P -



More information about the Comp.unix.wizards mailing list