Strange behaviour of awk

David Huelsbeck dph at lanl.gov
Mon Feb 27 15:25:48 AEST 1989


>From article <497 at eutrc3.UUCP>, by wsinkees at eutrc3.UUCP (Kees Huizing):
> 
> In the use of the UNIX filter "awk" I encountered the following problem.
> I want to save a line of input except the first field into a variable
> for later use.  So I empty the first field and then assign the modified
> record to the variable.
> But how curious!  When I try the test case
> 	{$1 = "" ; x = $0 ; print x}
> on the input
> 	Tom Dick Harry
> I just get :  
> 	Tom Dick Harry
> Testing the value of $0 by printing it
> 	{$1 = "" ; print}
> yields the expected output
> 	 Dick Harry
> So my solution is:
> 	{$1 = "" ; print >"/dev/null" ; x = $0 ; print x}
> And this works!, yielding
> 	 Dick Harry
> 
> Now I have two questions:
> 1. How can the value of $0 depend on whether it has been printed or not?
>    Is this a bug, or do I overlook some mechanism of awk?


It is a fairly well known bug in the BSD 4.2 version of awk that 
assignments to $1-$n don't change the value of $0.  

I'd never seen or tried the trick of printing $0.
How did you happen to think of this?



> 2. Is there a direct way to get $2, $3, .... until the end of the line (record)
>    without the somewhat dirty change of $1?  This was my original problem.
> 

You could use a "for (i=2; i <= NF; i++) { x = x $i }" but you'll loose
the field separators.  If you know that they'll always be some set bit
of whitespace like space or tab they're easy to replace.  Or pehaps an
sscanf that through the first field into a dummy and the rest into x.

> P.S. We have Ultrix 2.2 (appr. Unix BSD); I don't know how "new" our awk is.
> 

I don't know about 2.2 but the original Ultrix awk was bug for bug
compatable with BSD 4.2 awk.  This is not really surprising; I think
the code was exactly the same. 

> Kees Huizing              wsinkees at eutrc3.UUCP -or- wsdckees at heitue5.BITNET
> Dept. of Math. and Comp. Sc. - Eindhoven Univ. of Techn. - Eindhoven
>                     T H E     N E T H E R L A N D S


-dph

fodder
fodder
fodder
fodder
fodder
fodder
fodder
fodder
fodder
fodder
fodder
fodder
fodder
fodder
fodder
fodder
fodder
fodder
fodder
fodder
fodder
fodder
fodder
fodder
fodder
fodder
fodder
fodder
fodder
fodder
fodder
fodder
fodder
fodder
fodder
fodder



More information about the Comp.unix.questions mailing list