How to pass shell variables to awk?

Mark Harrison harrison at necssd.NEC.COM
Thu Apr 11 00:07:10 AEST 1991


In article <1991Apr8.223119.2318 at elroy.jpl.nasa.gov>,
pjs at euclid.jpl.nasa.gov (Peter Scott) writes:

> Maybe this one should be in the FAQ;

I will submit the following text to the FAQ list...
Question:  How do I submit a FAQ to the FAQ list? :-)

#
# This shell script provides several answers to the question
#          "How can I pass shell variables to awk?"
#

foo=123
bar=456
foostr=hello
barstr=world
twowords="hello world"

# 1.  Surround the environment variables with single quotes.  This
#     causes awk's first argument to be a single string, composed
#     of quoted strings interspersed with values of shell variables.
#     They are treated as one argument because there are no unquoted
#     spaces.

awk 'BEGIN {print 1, '$foo' + '$bar'}' </dev/null
#   ^^^^^^^^^^^^^^^^^^%%%%^^^^^%%%%^^^
#    ^                 ^   ^    ^   ^
#    |                 |   |    |   |
#    |                 +---|----+---|------------ substituted vars
#    +---------------------+--------+------------ quoted strings

# 2.  Set an internal awk variable on the command line.  While this
#     is documented in "old" awk, on my system it only seems to work
#     with "new" awk (nawk).

nawk 'BEGIN {print 2, foo + bar}' foo=$foo bar=$bar </dev/null
awk 'BEGIN {print 3, foo + bar}' foo=$foo bar=$bar </dev/null

# 3.  To use the environment variable as a string, It must have
#     double quotes around the single quotes.  If it does not,
#     then the text of the environment variable is treated as
#     an awk variable instead of as a constant.
#
# wrong: translates to {print hello, world}, printing the values
#        of the variables _hello_ and _world_ (both zero)
#
awk 'BEGIN {print 4, '$foostr', '$barstr'}' </dev/null
#
# right: shell vars are quoted, making them strings
#
awk 'BEGIN {print 5, "'$foostr'", "'$barstr'"}' </dev/null

# 4.  You will have problems if your environment variable
#     contains spaces.  The spaces embedded in the concatenated
#     string will cause awk to only catch the first part of
#     the command string, probably resulting in a syntax error.
#     If you set the awk variable on the command line, be sure
#     to enclose it in quotes.

# Syntax error:
awk 'BEGIN {print 6, "'$twowords'"}' </dev/null
# OK:
nawk 'BEGIN {print 7, twowords}' twowords="$twowords" </dev/null
-- 
Mark Harrison             harrison at ssd.dl.nec.com
(214)518-5050             {necntc, cs.utexas.edu}!necssd!harrison
standard disclaimers apply...



More information about the Comp.unix.questions mailing list