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 gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to match a variable's value in AWK? 1

Status
Not open for further replies.

micotao

Programmer
Jun 16, 2004
33
CN
Hi all:
say,there is such a awk statment in a "test.sh" file:
hostname_1=`hostname`
IP=`cat /etc/hosts | awk '{ if ($2==hostname_1) print $1}'`
echo $IP

the IP of hostname_1 in /etc/hosts is 165.167.189.21
but WHY IT OUTPUTS a blank line?????
WHY IP cannot get the corresponding value in the /etc/hosts???
Thanks!!!
This is in very urgent need!!
 
Try either this:
IP=`awk '{if($2=="'$hostname_1'")print $1}' /etc/hosts`
or this:
IP=`awk -v hostname_1=$hostname_1 '{if($2==hostname_1)print $1} /etc/hosts'`

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ222-2244
 
PHV:I tried your two ways, but it doesn't work . For this:IP=`awk '{if($2=="'$hostname_1'")print $1}' /etc/hosts`
It WORKS.
but the second:IP=`awk -v hostname_1=$hostname_1 '{if($2==hostname_1)print $1} /etc/hosts'` , I got such output:
awk: syntax error near line 1
awk: bailing out near line 1

THANKS PHV,but could you tell me the secret behind this???
 
Sorry for the typo:
IP=`awk -v hostname_1=$hostname_1 '{if($2==hostname_1)print $1}' /etc/hosts`

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ222-2244
 
Hi, PHV:
This time I tried your way, but also it outputs:
awk: syntax error near line 1
awk: bailing out near line 1
Can we use the hostname_1=$hostname_1 directly ?
Thanks very much......
 
$hostname_1 is a shell variable, not an awk one.
I don't understand the syntax error after the typo correction. You may try using nawk instead of awk.

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ222-2244
 
Thanks so much for PHV.This time, by using "nawk", it WORKS.
but why? any secret or suggestion?
 
Because the -v varname=value command line syntax is not implemented in the legacy old awk.
I guess you're on Solaris.

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ222-2244
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top