awk - take variables out to shell

Hi,
How could we take the value of awk variables out to shell?
I know the following methods

1. awk '{print $1}' < file | read a
    echo $a 
2. a=`awk '{print $1}' < file`
    echo $a

Please let me know if there are any other methods.

Also, how do we take more than 1 variable value out from an awk command? Is there any way to do that?:confused:

regards,
Thumban

Try this...

#!/bin/bash
val="a b c d"
val1=$( echo $val | awk '{print $1}')
echo $val1
 
#Multiple values. 
val_arr=( $( echo $val | awk '{print $1,$2,$3,$4}') )
echo ${val_arr[0]}
echo ${val_arr[1]}
echo ${val_arr[2]}
echo ${val_arr[3]}

HTH
--ahamed

Sorry Ahamed, didin't work :frowning:

Every value went to the 0th element in the array; nothing is getting assigned to 1st, 2nd and 3rd elements.

Thanks!
Thumban

Does your set command support -A option? If so, try this...

set -A val_arr $( echo $val | awk '{print $1,$2,$3,$4}' )

If not, you can always use this...

i=0
for val in $( echo $val | awk '{print $1,$2,$3,$4}' )
do
  val_arr[$i]=$val
  ((i=i+1))
done

--ahamed

Thanks Ahamed :smiley: