Operating System - HP-UX
1748199 Members
2799 Online
108759 Solutions
New Discussion юеВ

Re: Awk and assigning values to multiple variables

 
SOLVED
Go to solution
Scott Frye_1
Super Advisor

Awk and assigning values to multiple variables

I have a simple need that I know I can resolve with a loop but I want to know if there is a way to do it without looping.

My file has one line from TOP
0 ? 37 root 152 20 0K 1888K run 247:32 0.58 0.58 vxfsd

All I want to do is assign each piece of this line to a seperate variable. I could do
awk'{print $1" "$2 " "$3}' toptest.txt | while read var1 var2 var3; do
do whatever
done

but I would like to stay away from the loop since there is (and will only be) one line of data
9 REPLIES 9
Steven E. Protter
Exalted Contributor

Re: Awk and assigning values to multiple variables

var1=$(awk'{print $1}' toptest.txt)
var2=$(awk'{print $2}' toptest.txt)
var3=$(awk'{print $3}' toptest.txt)

This should populate the variables without using a loop.

SEP
Steven E Protter
Owner of ISN Corporation
http://isnamerica.com
http://hpuxconsulting.com
Sponsor: http://hpux.ws
Twitter: http://twitter.com/hpuxlinux
Founder http://newdatacloud.com
Scott Frye_1
Super Advisor

Re: Awk and assigning values to multiple variables

That is another way, but I have 13 to do. I'm looking for the most efficient way. What do you think about doing 13 variables that way?
c_51
Trusted Contributor

Re: Awk and assigning values to multiple variables

being your file has just one line,
the simplest way with just using the shell, would be:
cat file | read var1 var2 var3 rest
print "$var1 $var2 $var3" #just to test

and if you don't mind reading from right to left:

read var1 var2 var3 rest < yourfile
Stuart Abramson
Trusted Contributor

Re: Awk and assigning values to multiple variables

I think that you can do:

cat file | while read v1 v2 v3 ... v13
do
commands
end
Michael Schulte zur Sur
Honored Contributor
Solution

Re: Awk and assigning values to multiple variables

Hi,
what about
read var1 var2 var3 < toptest.txt
?

greetings,

Michael
c_51
Trusted Contributor

Re: Awk and assigning values to multiple variables

and you could put them all into an array:
set -A array $(print ${array[0]}
c_51
Trusted Contributor

Re: Awk and assigning values to multiple variables

and if you don't need your positional variables anymore:

set -- $(yourfile)

print $1 $2

c_51
Trusted Contributor

Re: Awk and assigning values to multiple variables

oops

should have been

set -- $(
print $1 $2

forgot the < in $(
Scott Frye_1
Super Advisor

Re: Awk and assigning values to multiple variables

I'm going for the
read var1 var2 var3 < toptest.txt
method.

Thanks for all the input!!

Scott