possible awk bug

carl carl at bdaemon.UUCP
Sat Apr 13 13:19:24 AEST 1985


I apologize for not answering the following by mail, but have managed to
loose the original message (we have but a 40 Mbyte disk on our Pixel 100/AP
and news articles are expired after seven days).  Anyway

{harvard,seismo,ut-sally,ihnp4!packard}!topaz!jaffe writes:

> It seems to me that the line:
> 
> echo "This is a test" | awk {$1 = "Foo"; print}
> 
> should print out "Foo is a test" but all I get when I try it is the
> original line.
> 
> Is this a bug in awk? 

No, it is not.  The shell is the problem.  As written, the assignment

	$1 = "Foo"

will substitute "This" for $1 and, depending on the version of awk, will
either ignore the assignment or produce an error message because the user
is asking for

	This = "Foo"

which is obviously non-sense.

The solution is very simple, namely enclose the awk statements in single
quotes.  Thus

	echo "This is a test" | awk '{$1 = "Foo"; print}'

will produce the desired result since the single quotes remove the special
meaning of all shell meta-characters and there is no longer a conflict
between the first argument passed to awk and the way fields are referred
to in awk.

If you are using the System V (or System III) shell an easy way to test
this sort of thing from the terminal is to first execute

	$ set -x
	$ echo ........

not forgetting to do a

	$ set +x 

after you are done experimenting.

Kernighan & Pike have many examples of how to handle the interaction
between the shell and awk and sed and others, and I strongly recommend
studying that book.

Carl Brandauer
daemon associates, Inc.
1760 Sunset Boulevard
Boulder, CO 80302
303-442-1731
{allegra|amd|attunix|cbosgd|ucbvax|ut-sally}!nbires!bdaemon!carl



More information about the Comp.unix.wizards mailing list