[comp.unix.shell] awk variables

oscarh@hpdmd48.boi.hp.com (Oscar Herrera) (11/30/90)

>I am trying to use both shell variables and awk variables in the 
>same awk call, but I cannot get both to work correctly.  I have tried
>many variations of quoting and have had no success.  The statement
>I want to use is :
>
>	awk "NR == $line_num {print $1}" filename
>
>where $line_num is a script variable (an integer) and $1 is the 
>awk variable for the first field.  I would even like to get more fancy 
>and say {print $n} where $n is a shell variable like "$1", "$2",...
>
>Does anyone know how this can be done in the C-Shell?
>Thanks.
>----------

	try

 	awk 'NR == '$line_num '{print $1}' filename

	Having $line_num not enclosed in single quotes should 
	allow the shell to get a hold of it and stick the variable value
	in its place.  I did not test this myself, but I vaguely
	remember this from a class long ago.

fuchs@it.uka.de (Harald Fuchs) (12/01/90)

oscarh@hpdmd48.boi.hp.com (Oscar Herrera) writes:
>>I am trying to use both shell variables and awk variables in the 
>>same awk call, but I cannot get both to work correctly.  I have tried
>>many variations of quoting and have had no success.  The statement
>>I want to use is :
>>
>>	awk "NR == $line_num {print $1}" filename
>>
>>where $line_num is a script variable (an integer) and $1 is the 
>>awk variable for the first field.

>	try

> 	awk 'NR == '$line_num '{print $1}' filename

>	Having $line_num not enclosed in single quotes should 
>	allow the shell to get a hold of it and stick the variable value
>	in its place.

This won't work.
  awk 'NR == '$line_num '{print $1}' filename
                       ^ Here's the bug
Awk expects its script to be the first argument, and when there's a
blank after $line_num (or within an expanded shell variable like that)
awk will see two arguments. Don't put blanks around $line_num and, if
your shell variable might contain blanks, enclose it by double quotes:
  awk 'NR == '"$line_num"'{print $1}' filename
--

Harald Fuchs <fuchs@it.uka.de> <fuchs%it.uka.de@relay.cs.net> ...
<fuchs@telematik.informatik.uni-karlsruhe.dbp.de>   *gulp*

davidsen@sixhub.UUCP (Wm E. Davidsen Jr) (12/03/90)

  awk reads variables off the command line. They appear between the
commands (or name of the command file) and the filename(s) to be
processed. That means you might specify the input filename, using '-' if
stdin is what you want (not all versions need this, all accept it).

As:

  awk '$3 == BAR { print $2 }' BAR=$5 file
                               ^^^^^^
                               Sets BAR in the awk environment

-- 
bill davidsen - davidsen@sixhub.uucp (uunet!crdgw1!sixhub!davidsen)
    sysop *IX BBS and Public Access UNIX
    moderator of comp.binaries.ibm.pc and 80386 mailing list
"Stupidity, like virtue, is its own reward" -me