Operating System - HP-UX
1748151 Members
3835 Online
108758 Solutions
New Discussion юеВ

Re: Can you pass vatiables to awk?

 
Jamie Collins
Advisor

Can you pass vatiables to awk?

In a shell script:

server=jamie

awk '{if ($2 = $server).....
13 REPLIES 13
Sridhar Bhaskarla
Honored Contributor

Re: Can you pass vatiables to awk?

Hi Jamie,

Yes. You will have use -v flag with awk to pass them. For ex.,

string="Sridhar"
echo "test" |awk -v name=$string '{print name}'

-Sri
You may be disappointed if you fail, but you are doomed if you don't try
Jamie Collins
Advisor

Re: Can you pass vatiables to awk?

I got it to work with the following as well:

awk '{if ($2 = "'$server'"...

Thanks
Sridhar Bhaskarla
Honored Contributor

Re: Can you pass vatiables to awk?

Yeah.. its' the same way

server=jamie

awk -v server=$server '{if ($2 = $server)...


-Sri
You may be disappointed if you fail, but you are doomed if you don't try
Jamie Collins
Advisor

Re: Can you pass vatiables to awk?

Actually it dosn't work either way...

Instead of the string 'jamie' I get:

if $2 = server

I tried it with $server and "$server" but it doesn't work...
A. Clay Stephenson
Acclaimed Contributor

Re: Can you pass vatiables to awk?

That's because in awk only positional variables ($1,$2, ...) get the $; all user defined variables do not use the $ prefix.
If it ain't broke, I can fix that.
Sridhar Bhaskarla
Honored Contributor

Re: Can you pass vatiables to awk?

I simply cut and pasted your line. I didn't realize you had a $ in front of $server. Look at my first example where I didn't use $ in front of 'name'.

-Sri
You may be disappointed if you fail, but you are doomed if you don't try
Muthukumar_5
Honored Contributor

Re: Can you pass vatiables to awk?

Yes. We can do this as,


echo "jamie" | awk '{ if ( $1 == server ) print "ok" }' server=jamie

It will pass that environment variable of server with jamie string there.

You can more check as,

echo "hai" | awk '{ print server }' server=jamie

HTH.
Easy to suggest when don't know about the problem!
Jamie Collins
Advisor

Re: Can you pass vatiables to awk?

Here's what I get... (changed the variables to do a time range instead...)

server_time="07:08:55"
awk -v time=$server_time {if ($9 < time && $10 > time)

when I debug it looks like this:

awk -v time=07:08:55 {if ($9 < time && $10 > time)

shouldn't the time be replaced with the value of the time variable?
Muthukumar_5
Honored Contributor

Re: Can you pass vatiables to awk?

You can also --assign var=value on awk too.

It is as,

echo "hai jamie" | awk --assign server=jamie '{ if ( $1 == server ) print "OK" }'

Else try awk -v =value

see man awk.

HTH.
Easy to suggest when don't know about the problem!