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!

Grap one entry out of file 2

Status
Not open for further replies.

appi

IS-IT--Management
Mar 17, 2003
296
0
0
CH
Hello Unix Community

I just have a cahllenge to grap out only one entry out of a /etc/hostname file
By now - on a single system - it works fine
We use
VAR='awk -v myvar=${HOST} 'match($2,myvar){print $1}' /etc/hosts'
nslookup $VAR

But if we have a RAC Cluster or different Lan sehgments we do have the hostname two ore more times which gives us a Variable with 2 or more IP Adresses which let nslookup fail.

thanks
Uwe
 
What about this ?
... 'match($2,myvar){print $1[!];exit[/!]}' ...

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
Hi

Or this ?
Code:
for VAR in `awk -v myvar=${HOST} 'match($2,myvar){print $1}' /etc/hosts`; do
  nslookup $VAR;
done

Feherke.
feherke.github.io
 
Thanks PH
but what if the requested hostname is not the first in list ?

I only need the one for the real requested name
If we have a block in this file like

xxx.xxx.xxx.xxx myhost.domain myhost
yyy.yyy.yyy.yyy myhost-priv
zzz.zzz.zzz.zzz myhost-vip

I only want the ip of myhost (xxx.xxx.xxx.xxx)

thanks again
Uwe
 
Hi

So the searched word may or may not be in [tt]$2[/tt]. The search all fields starting with the 2[sup]nd[/sup] :
Code:
awk -v myvar="$HOST" '{for(i=2;i<=NF;i++)if($i==myvar){print $1;exit}}'

Feherke.
feherke.github.io
 
Thanks Feherke

this works fine now. I just extend it with
grep $HOST /etc/hosts | grep -v '#' | awk -v myvar="$HOST" '{for(i=2;i<=NF;i++)if($i==myvar){print $1;exit}}'

to secure also commented lines with same hostname. This looks good now

regards
Uwe
 
Why all those grep ?
Code:
awk "/$HOST/{sub(/#.*/,\"\");for(i=2;i<=NF;i++)if(\$i==\"$HOST\"){print $1;exit}}" /etc/hosts

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
Oops, sorry for the typo:
Code:
awk "/$HOST/{sub(/#.*/,\"\");for(i=2;i<=NF;i++)if(\$i==\"$HOST\"){print \$1;exit}}" /etc/hosts

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
Thanks PHV -
this also works fine and is better capsuled as my pipes

regards
Uwe
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top