Operating System - HP-UX
1834843 Members
1779 Online
110070 Solutions
New Discussion

storing columns in different variables

 
SOLVED
Go to solution
Anand_30
Regular Advisor

storing columns in different variables

Hi,

Please find attached a file which has 2 columns. I need to store the column values in 2 different variables and use them in a SHELL script. I have an excutable which takes the coulmn values as parameters.

Thanks,
Andy

3 REPLIES 3
A. Clay Stephenson
Acclaimed Contributor
Solution

Re: storing columns in different variables

Trivially simple:

MYFILE=myfile.txt

cat ${MYFILE} | while read A B
do
echo "A = \"${A}\" B = \"${B}\""
done
If it ain't broke, I can fix that.
Chris Vail
Honored Contributor

Re: storing columns in different variables

Clay's script is, as he said, trivially simple. Its is limited to parsing the table from the beginning to the end. But what if you wanted to start at the end, and work up to the beginning? Here's a (probably needlessly) complex way to do this:

#!/usr/bin/ksh
LENGTH=`wc -l $FILE|awk '{ print $1 }'`
while test "$LENGTH" -ge "1"
do
LINE=`head -"$LENGTH" $FILE|tail -1`
A=`echo $LINE|awk '{ print $1 }'`
B=`echo $LINE|awk '{ print $2 }'`
(( LENGTH = "$LENGTH" - "1" ))
done

Another advantage (if there is one) is that not every version of Unix has the read command. But every one that I've ever seen has head, tail, and awk. Some versions (System V derivations, like old SCO) don't have wc either. If so, use
LENGTH=`pr -n -t $FILE|tail -1|awk '{ print $1 }'`
instead of the previous LENGTH statement. This uses up a lot more clock cycles than Clays script, but is portable across every version of Unix that I've ever seen. Its handy for log files.




Chris
john korterman
Honored Contributor

Re: storing columns in different variables

Hi,
this will probably also work:

# A=$(cut -f1 infile)
# B=$(cut -f2 infile1)

regards,
John K.
it would be nice if you always got a second chance