Languages and Scripting
Showing results for 
Search instead for 
Do you mean 

how to substitute variable in awk.

SOLVED
Go to Solution
Frequent Advisor

how to substitute variable in awk.

Hi friends,

I want check if all my servers are up by this script, can any one help me with 2 issues

1) How to insert variable in awk (awk '$1 == "$a" { print $0 } ' /etc/hosts )

2) How to set timeout for ping ?

#!/bin/sh

for a in
` sed -n '/202/p' /usr/scripts/ping_server.sh | awk ' { print $1 } '`
do
echo pinging $a

flag=`ping $a -n 3`
echo $flag | grep -i '0% packet loss'
echo $?

if [ "$?" -eq 0 ]
then

h=`awk '$1 == "$a" { print $0 } ' /etc/hosts `
echo " $h Host Alive "

fi

done



Waitn for u r responce.

Rgds
Ankur
1 ACCEPTED SOLUTIONS
Highlighted
Honored Contributor Honored Contributor

Re: how to substitute variable in awk.


man awk tells you to use -v parameter

awk -v myvar=$a '{print myvar}' filename

But
A far better method to check to see if your hosts are up is to use ruptime.

vi /etc/rc.config.d/netdaemons
set RWHOD=1
start rwhod

then, define host equivalence for your machines.
$ ruptime

It will run uptime on all your remote systems and list them all at once. It also shows the load on each machine.




5 REPLIES
Highlighted
Honored Contributor Honored Contributor

Re: how to substitute variable in awk.


man awk tells you to use -v parameter

awk -v myvar=$a '{print myvar}' filename

But
A far better method to check to see if your hosts are up is to use ruptime.

vi /etc/rc.config.d/netdaemons
set RWHOD=1
start rwhod

then, define host equivalence for your machines.
$ ruptime

It will run uptime on all your remote systems and list them all at once. It also shows the load on each machine.




Honored Contributor Honored Contributor

Re: how to substitute variable in awk.

try awk '$1 == "'"$a"'" { print $0 } ' /etc/hosts `
Honored Contributor Honored Contributor

Re: how to substitute variable in awk.

You can also use this:

export A=2
awk '{p=ENVIRON["A"];print p}'

2

Frequent Advisor

Re: how to substitute variable in awk.

thanks laurant and steve for ur quick responces.
Im happy.
For laurant : awk: Field $() is not correct.
The input line number is 1. The file is /etc/hosts.
The source line number is 1.

Steve's thing worked , but had to some tweakin.

Regards
Ankur
Frequent Advisor

Re: how to substitute variable in awk.


This is how we can address variable "a" in awk.
awk '$1 == ENVIRON["a"]
{ print $0 } ' /etc/hosts