How to pass shell variables to awk?

Robert Hartman rhartman at thestepchild.sgi.com
Wed Apr 10 03:24:40 AEST 1991


In article <1991Apr8.223119.2318 at elroy.jpl.nasa.gov> pjs at euclid.jpl.nasa.gov writes:
>Maybe this one should be in the FAQ; I know it came through here
>several months ago, but I forgot the answer until, of course, I
>wanted to do it myself.
>
> ... if I have
>some (csh) variable foo and I want awk to recognize it, e.g.
>awk file '{print $1-?$foo?}', what would I use instead of ? and ? ?

Use single quotes:

	awk '{... '$foo'...}' file
                  ^    ^
Since there is no white space between the quoted expressions and the (now
unquoted) shell var, the shell treates the whole program argument as just
one word.  Of course, you can't have white space in the variable value here.
If you need to guarantee against white space, use:

	awk '{... '"$foo"'...}' file

since variable expansion takes place within double quotes.

-r


ps.  I think this does qualify as an FAQ.  Second time I've answered it this
month.  (Once in c.u.shells.)



More information about the Comp.unix.questions mailing list