awk & variables

Bill Poser poser at csli.Stanford.EDU
Sat May 27 16:53:41 AEST 1989


In article <23206 at dhw68k.cts.com>, jaff at dhw68k.cts.com (Mark Jaffe) writes:
> Awk seems to be lacking something, but maybe it's really there.  I want to
> match a pattern that I don't know until I execute the script, so I want to
> pass in a pattern to match in a variable.  I can't get this to work!  Here's
> what I'm doing, on a Sun:
>  .
>  .
> SYSVER=`awk '{print $3}' < /etc/motd`
>  .
> awk ' $0 ~ $SYSVER { print substr($0, 3, length - 2) } ' < cs35if.h > cs35.if 
>  . 

The problem is not with AWK, it is with the way you are quoting the
AWK program. Single quotes in the shell prevent evaluation of variables.
So $SYSVER is the pattern that AWK tries to match, not the VALUE of SYSVER.
To get around this, you need to change the single quotes around the AWK
program to double quotes. However, the shell will now evaluate the
$0 that is intended to be evaluated by AWK. To prevent this, quote the
$ with a backslash so that the shell will leave it alone.

A simple example of all of this (that I know to work) is the following,
which is my address book lookup command:

awk " BEGIN {RS = \"\"} /$1/ {printf(\"%s\\n\\n\",\$0)}" < $HOME/misc/add

The $1 is the command line argument to the shell script. The $0
is the "line" (actually a block of text due to the resetting of RS)
read by AWK.

						Bill Poser



More information about the Comp.unix.wizards mailing list