[comp.unix.questions] accessing shell variables from within awk?

rscott@eta.unix.ETA.COM (Rich Scott) (09/20/88)

	How can I access a shell variable (to wit, a few environment
variables) from within "awk"? I've tried various combinations of
shell quoting, and whatnot, to no avail. Does any version of awk
have a shortcut to get at it's environment? BTW, I'm running SunOS
3.5, if it matters much.

---
	Rich Scott	     uucp:  {rutgers,amdahl,ihnp4}!meccts!eta!rscott
	ETA Systems	   domain:  rscott@eta.eta.com
	Saint Paul, MN	     arpa:  eta!rscott@uxc.cso.uiuc.edu
					 -or- 	rscott@gonzo.eta.com
	"Heck-a-slammin'"  - S. Easton/P.R. Nelson

guy@gorodish.Sun.COM (Guy Harris) (09/20/88)

> 	How can I access a shell variable (to wit, a few environment
> variables) from within "awk"? I've tried various combinations of
> shell quoting, and whatnot, to no avail. Does any version of awk
> have a shortcut to get at it's environment?

Well, the "new awk" might, but I don't know how many UNIX systems offer it yet.
"awk" doesn't have any mechanism for getting at the UNIX environment (i.e., the
thing that "export" in the Bourne and Korn shells, and "setenv" in the C shell,
affect).

You can put assignments on the command line:

     "awk" variables may be set on the command line using arguments
     of  the  form  "variable=value".  This sets the "awk" variable
     "variable" to "value"  before  the  first  record  of  the  next
     filename argument is read.

which might be a way to pass them to "awk", e.g.

	awk -f awkfile foo="$foo"

which sets the "awk" variable "foo" to the value of the shell variable "foo".

> BTW, I'm running SunOS 3.5, if it matters much.

Not a lot; that "awk" is basically the S5R2 "awk", but the feature in question
is, I think, in the 4BSD "awk" as well.

karish@hanauma.stanford.edu (Chuck Karish) (09/20/88)

In article <473@diamond.unix.ETA.COM> rscott@eta.unix.ETA.COM (Rich Scott)
writes:
>	How can I access a shell variable (to wit, a few environment
>variables) from within "awk"?

The awk command is usually written inside single quotes.  Use more
quotes to expose the shell variables you need.  The following program will
print a user's name and user ID number:

USRNAME="fred"
export USRNAME

awk -F':' '$1 ~ /'$USRNAME'/{print $1, $3}' /etc/passwd

Chuck Karish    ARPA:   karish@denali.stanford.edu
                UUCP:   {decvax,hplabs!hpda}!mindcrf!karish
                USPS:   1825 California St. #5   Mountain View, CA 94041

ok@quintus.uucp (Richard A. O'Keefe) (09/20/88)

In article <473@diamond.unix.ETA.COM> rscott@eta.unix.ETA.COM (Rich Scott) writes:
>
>	How can I access a shell variable (to wit, a few environment
>variables) from within "awk"?

Try
	awk -f script var=value... var=value file...
This is in the SunOS manual page, and worked on a 4.2 system which didn't
have it in the manual page.  Or use a temporary file:
	cat >$$.awk <<EOF
	# put your script here
	EOF
	awk -f $$.awk ....
	rm $$.awk

dhesi@bsu-cs.UUCP (Rahul Dhesi) (09/20/88)

>How can I access a shell variable (to wit, a few environment
>variables) from within "awk"?

--cut here--cut here
#! /bin/sh
# How to use env variables from an awk script.  Just enclose the awk
# command in double quotes.  This will not work if the awk script is
# in a separate file.  Tested under 4.3BSD.

  awk "\
     BEGIN {mypath=\"$PATH\"; \
     printf \"my path is: [%s]\n\", mypath}" < /dev/null
--cut here--cut here

-- 
Rahul Dhesi         UUCP:  <backbones>!{iuvax,pur-ee,uunet}!bsu-cs!dhesi

meo@stiatl.UUCP (Miles O'Neal) (09/21/88)

In article <473@diamond.unix.ETA.COM>, rscott@eta.unix.ETA.COM (Rich Scott) writes:
> 
> 	How can I access a shell variable (to wit, a few environment
> variables) from within "awk"? ...

As a matter of fact, this is from a Sun 386i running 4.0,
but should work with any real awk. We use it also under System V on
a Convergent.

usernum=`awk -F: '/^'$1'/ { print $3 }' /etc/passwd

This is from a Bourne shell script we use. The $1 could just as
easily be $fred or any variable name.

finn@eleazar.dartmouth.edu (Andy Behrens) (09/24/88)

In answer to the question "How can I access a shell variable from within
awk", guy@gorodish.Sun.COM (Guy Harris) writes:
>
> You can put assignments on the command line,
> which might be a way to pass them to "awk", e.g.
>
>	awk -f awkfile foo="$foo"

If you are going to use this feature, be aware that many versions of awk
only recognize command-line assignments if they are followed by at least
one filename.  If you want awk to read from the standard input, explicitly
name it with '-', e.g.

	ls -l | awk -f awkfile foo="$foo" -

--
"Christ died for our sins.  Dare we make his martyrdom meaningless by
not committing them?"
					Andy Behrens
					andyb@burcoat.uucp
					(soon: andyb@coat.uucp)

internet: andyb%coat@dartmouth.edu
uucp:     {harvard,decvax}!dartvax!coat!andyb
bitnet:   andyb%coat@dartcms1
RFD 1, Box 116, East Thetford, Vt. 05043		 (802) 649-1258

pdvbld@prcpto.UUCP (Betsy Dunphy) (09/27/88)

> How can I access a shell variable (to wit, a few environment
> variables) from within "awk"? I've tried various combinations of
> shell quoting, and whatnot, to no avail.......

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)}'


$HOME is expanded by the shell by the notation of the single-quotes.  The
trick is the double-quotes - these denote the result as a string.  Otherwise,
the value of $HOME would be treated as a variable (an unitialized variable).

This works in both bourne shell and csh (of course! :-)) and was tried on
both a Masscomp 5500 3.1.B RTU and SUN 3/160 under 3.2.


---------------------------------------------------------------------
Betsy Dunphy            |
PRC                     |
600 West Services Road  |  The usual disclaimer here......
Washington, DC 20041    |
703-883-5138            |
prcpto@pdvbld.UUCP      |
---------------------------------------------------------------------

jes@eniac.seas.upenn.edu (Joe Smith) (09/27/88)

In article <313@prcpto.UUCP> pdvbld@prcpto.UUCP (Betsy Dunphy) writes:
>> How can I access a shell variable (to wit, a few environment
>> variables) from within "awk"? I've tried various combinations of
>> shell quoting, and whatnot, to no avail.......
>
>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.


Frank Kolakowski (a.k.a. Lee)
____________________________________________________________________________
|c/o jes@eniac.seas.upenn.edu			||	Univ. of Penna.     |
|kolakowski%c.chem.upenn.edu@relay.upenn.edu	||	Dept of Chemistry   |
|bcooperman.kolakowski@bionet-20.arpa		||	231 South 34th St.  |
|AT&T:	1-215-898-2927				||	Phila, PA 19104     |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Well, O.K. I'll compromise with my principles because of EXISTENTIAL DESPAIR!
=============================================================================


Joe Smith
jes@eniac.seas.upenn.edu

University of Pennsylvania
Department of Chemistry
231 S. 34th Street
Philadelphia, PA 19104
(215) 898-4797

ljz%fxgrp.fx.com@ames.arc.nasa.gov (Lloyd Zusman) (09/28/88)

In article <5321@netnews.upenn.edu> jes@eniac.seas.upenn.edu (Joe Smith) writes:

   Path: fxgrp!ames!ncar!mailrus!eecae!netnews.upenn.edu!eniac.seas.upenn.edu!jes
   In article <313@prcpto.UUCP> pdvbld@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@fx.com
  Master Byte Software                  or ljz%fx.com@ames.arc.nasa.gov
  Los Gatos, California                 or fxgrp!ljz@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 ]

madd@bu-cs.BU.EDU (Jim Frost) (09/29/88)

In article <473@diamond.unix.ETA.COM> rscott@eta.unix.ETA.COM (Rich Scott) writes:
|
|	How can I access a shell variable (to wit, a few environment
|variables) from within "awk"?

The simplest way is:

set shellvar = "foo"

awk 'BEGIN { foo == ' $shellvar ' ; \
             print  foo             \
           }'

You could similarly unquote and quote for every occurance of "foo".

jim frost
madd@bu-it.bu.edu