variables in awk

Dan Kozak dbk at mimsy.UUCP
Thu Apr 27 15:43:09 AEST 1989


In article <10029 at burdvax.PRC.Unisys.COM> lang at sirius.PRC.Unisys.COM (Francois-Michel Lang) writes:

>Is there any way to do pattern-matching on an AWK variable?

>Now, the question is, what if I want to match not against
>a given string (which is fixed at "compile time"),
>but against an AWK variable, whose value can change
>in the course of the life of the AWK script.
>I can't find anything in any AWK documentation
>that tells me that this is possible, and, if so,
>how to do it.  Any pointers would be appreciated.

This is one of the additions to nawk (new awk) and is called dynamic
regular expressions.  The slashes around the usual kind of regular
expression, i.e. /foo/, indicate that it is a constant.  So you get
rid of those and put the variable's name in the same place.  Here's an
(admitedly contrived) example:

BEGIN { ss = "dbk" }

$1 ~ ss { print; 
	  ss = "jrl"; }

When run like this: who | nawk -f awk.tst it lists the first occurance
of my logon in the who listing and any subsequent occurances of jrl.
Mind you, there is one difference between this and constant regular
expressions that I've found (bug or feature? YOU be the judge!).
Although you can specify a pattern like:

/jrl/ { print $3; }

you have to this with a dynamic regex:

foo = "jrl"
$0 ~ foo { print $3; }

i.e. you have to make the match explict.

Happy nawking!

#dan

dbk at mimsy.umd.edu
uunet!mimsy!dbk



More information about the Comp.unix.questions mailing list