accessing shell variables from within awk?
Lloyd Zusman
ljz%fxgrp.fx.com at ames.arc.nasa.gov
Wed Sep 28 06:23:21 AEST 1988
In article <5321 at netnews.upenn.edu> jes at eniac.seas.upenn.edu (Joe Smith) writes:
Path: fxgrp!ames!ncar!mailrus!eecae!netnews.upenn.edu!eniac.seas.upenn.edu!jes
In article <313 at prcpto.UUCP> pdvbld at prcpto.UUCP (Betsy Dunphy) writes:
>> How can I access a shell variable (to wit, a few environment
>> variables) from within "awk"? ...
>
>As I understand the question, the writer desires to be able to
>use environmental variables in awk functions like printf. The following
>example prints file paths:
>
> ls | awk '{printf("%s/%s\n","'$HOME'",$1)}'
>
The example posted here is *not* expansion of shell variables "within"
awk, but instead expansion of shell variables on the command line, which we
all know is possible.
According to the book "The Awk Programming Language" A. Aho et al., none
of the shell variables are accessible from within the language. So the only
option is to use the shell as a preprocessor as in the above example.
However, according to the same book, the following constructs will work:
#!/bin/awk -f
...
# The following runs the command 'echo $HOME' through
# the shell and captures its stdout output into the
# awk variable 'homedir'. Note that even though '$HOME'
# is evaluated by the shell, its value can be captured
# inside of your awk script. This only seems to work
# in the enhanced System 5 awk (sometimes called "nawk").
"echo $HOME" | getline homedir;
# Here's a way to simply print the value of an environment
# to stdout from within awk. This, too, only seems to
# work in the enhanced System 5 awk.
system("echo $HOME");
# This also prints the value of an environment variable to
# stdout, but it also seems to work in older versions of
# awk as well (at least it works under SunOS 3.5).
print | "echo $HOME";
# Be careful about the last two examples, as the stuff that
# goes to stdout may not appear when you think it should due
# to awk's buffering. For example, in my version of awk
# under SunOS 3.5, the following statements ...
print | "echo $SHELL"
printf("Hi there\n");
# ... produce the following stdout output:
#
# Hi there
# /bin/csh
#
# If you have the enhanced System 5 awk, I suggest using
# the 'getline' construct:
"echo $SHELL" | getline shell;
printf ("%s\nfoo bar\n", shell);
# It will print the information in the desired order.
...
--
Lloyd Zusman Internet: ljz at fx.com
Master Byte Software or ljz%fx.com at ames.arc.nasa.gov
Los Gatos, California or fxgrp!ljz at ames.arc.nasa.gov
"We take things well in hand." uucp: ...!ames!fxgrp!ljz
[ our Internet connection is down: use uucp or mail to the entry above it ]
More information about the Comp.unix.questions
mailing list