INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Member Login

HANDLE


PASSWORD
Remember Me
Forgot Password?

Come Join Us!

  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • Turn Off Ad Banners
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

E-mail*
Handle

Password
Verify P'word
*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Partner With Us!

"Best Of Breed" Forums Add Stickiness To Your Site
Partner Button
(Download This Button Today!)

Member Feedback

"...Just to let you know...what a great site you have. I posted a pretty generic question yesterday and have had 8 responses already, anyway thanks again and keep up the good work..."

Geography

Where in the world do Tek-Tips members come from?

AWK FAQ

Shell variables in awk

How can I access shell variables in awk
Posted: 19 Nov 01

You can use any of the following 3 methods to access shell variables inside an awk script ...

1. Assign the shell variables to awk variables after the body of the script, but before you specfiy the input

awk '{print v1, v2}' v1=$VAR1 v2=$VAR2 input_file

Note: There are a couple of constraints with this method;
- Shell variables assigned using this method are not available in the BEGIN section
- If variables are assigned after a filename, they will not be available when processing that filename ...

e.g.

awk '{print v1, v2}' v1=$VAR1 file1 v2=$VAR2 file2

In this case, v2 is not available to awk when processing file1.

2. Use the -v switch to assign the shell variables to awk variables.  This works with nawk, but not with all flavours of awk.  On my system (Solaris 2.6) -v cannot be used with /usr/bin/awk but will work with /usr/xpg4/bin/awk.

nawk -v v1=$VAR1 -v v2=$VAR2 '{print v1, v2}' input_file

3. Protect the shell variables from awk by enclosing them with "'" (i.e. double quote - single quote - double quote).

awk '{print "'"$VAR1"'", "'"$VAR2"'"}' input_file


Thanks to aigles for his comments.

Greg.

Back to AWK FAQ Index
Back to AWK Forum
My FAQ Archive
Email This FAQ To A Friend

My Archive