Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Scripting (awk) Help 2

Status
Not open for further replies.

AIXtexas

Technical User
Feb 5, 2002
80
0
0
US
Here is my simple script:

#!/bin/ksh

host=`hostname`

cat /etc/passwd | awk -F: '{if($3 == 0) print $1,"- $host"}'

Here is the output:

root - $host

The output I'm looking for is (the name of the host is tech3):

root - tech3

Apparently, awk is interpreting my “- $host”. What am I doing wrong? Thanks.

Shane
 
The single quotes on your argument to awk is preventing shell expansion of $host.

You have two (maybe three) options:
Code:
# 1. Use double quotes and escape 
# all of the special characters that 
# need to pass through to awk

cat /etc/passwd | awk -F: "\{if\(\$3 == 0\) print \$1,\"- $host\"\}"

# ugly, ain't it?

# 2. Close the single quotes before $host 
# and reopen after, exposing $host to shell
# expansion

cat /etc/passwd | awk -F: '{if($3 == 0) print $1,"- '$host'"}'

# a little better, but tricky for 
# anyone maintaining the code

# 3. If your awk is modern enough, or is nawk or gawk
# you can assign the variable value on the command line

cat /etc/passwd | awk -v host="$host" -F: '{if($3 == 0) print $1,"- ",host}'

# MUCH easier to read and maintain


- Rod

IBM Certified Advanced Technical Expert pSeries and AIX 5L
CompTIA Linux+
CompTIA Security+

Wish you could view posts with a fixed font? Got Firefox & Greasemonkey? Give yourself the option.
 
There's a 4th option: get awk to read the value of the wanted shell variable from the environment during the BEGIN phase:

Code:
HOST=`hostname`
export HOST

awk -F: 'BEGIN {host=ENVIRON["HOST"]} {if ($3==0) print $1,"- ",host}' /etc/passwd


HTH,

p5wizard
 
And a 5th! Use the command form of getline to read it in the BEGIN clause:
Code:
HOST=`hostname`
export HOST

awk -F: 'BEGIN {"echo \$HOST" | getline host} {if ($3==0) print $1,"- ",host}' /etc/passwd

- Rod

IBM Certified Advanced Technical Expert pSeries and AIX 5L
CompTIA Linux+
CompTIA Security+

Wish you could view posts with a fixed font? Got Firefox & Greasemonkey? Give yourself the option.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top