You can pass *anything* to awk: even in BEGIN!
Jerry Peek
jerryp at tektools.UUCP
Thu Sep 25 02:07:47 AEST 1986
In article <185 at motown.UUCP> jmr at motown.UUCP (John M. Ritter) writes:
> awk '
> BEGIN { TERM = "'$TERM'"; # From Environment
> VAR1 = "'$VAR1'"; # From Above
> VAR2 = "'"$VAR2"'"; # From Above: Note strange quotes!
...etc...
> } # End of BEGIN
>
> This method DOES allow initialization within the BEGIN block, and it is
> also as easy to use as $1 in a shell script...
>
> I can't think of anything that has been left out. This is using
> System V, r2.0v2 - I'd love to know if this works on other versions
> of Unix.
Seems like this should work everywhere (unless I'm missing something?); it's
dependent on the quoting behavior of the *shell*, not awk. You just have to
make sure that the shell plugs in the values before it invokes "awk".
I've been taking this a step farther, to let me define arbitrary variables
(or array members) within an "awk" BEGIN block. First, I write a
shell script which outputs strings of the form:
VAR = "some junk"
array["member 1"] = "VALUE 1"
array["member 2"] = "VALUE 2"
... these are the variable-assignment commands you want "awk" to do.
(They might include things that vary, day-to-day, like the output of "date"
or "who" or "uptime" or...) Let's call that program "mkawkvars".
Then, you put the "mkawkvars" output into your awk script. Use the shell's
command-substitution feature (backquotes or grave accents), like this:
awk "
BEGIN { `mkawkvars`"' }
{
...rest of awk script...
}'
The quoting is important. The first section of the script has doublequotes (")
around it. That's because:
- the command-substitution (`mkawkvars`) won't work if you enclose it
within singlequotes('`mkawkvars`').
- the mkawkvars script must output newlines after every
variable-assignment command. If you don't quote the
mkawkvars output at all, the newlines disappear; awk
will see all the variable assignments on one line, like this:
VAR = "some junk" array["member 1"] = "VALUE 1" array[...
... causing "awk: bailing out near line 2..." :-)
You can surround the first part of the BEGIN block with doublequotes, then
switch to singlequotes (as I did above) after `mkawkvars` has been executed.
This article is too long already, so I won't include any more examples.
If anyone's interested, though, send me mail and I'll send you a copy
of a working script.
--Jerry Peek, Tektronix, Inc.
US Mail: MS 74-900, P.O. Box 500, Beaverton, OR 97077
uucp: {allegra,decvax,hplabs,ihnp4,ucbvax}!tektronix!tektools!jerryp
CS,ARPAnet: jerryp%tektools at tektronix.csnet
Phone: +1 503 627-1603
More information about the Comp.unix
mailing list