LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   assigning column name to awk print in a loop (https://www.linuxquestions.org/questions/programming-9/assigning-column-name-to-awk-print-in-a-loop-834896/)

bashprog 09-28-2010 02:12 AM

assigning column name to awk print in a loop
 
I am trying to assign column number/name to awk print option in a loop. But this is not working here. Can you help

Code:


#!/bin/sh


STR='overt 0 1 1.3 2 2.5 3 3.6 4 4.9 5 5.7 6 6.3'

for i in `seq 3 2 13`

do

#      echo "val:" ;
        echo i=$i
        val=\$$i
        echo val=$val
        v1=`echo $STR | awk '{print $val;}'`
        echo $v1
done

I am trying to print values at col 3, 5, 7, 9, 11, 13 in example above, but this is not working. Any suggestions welcome. TIA.

ghostdog74 09-28-2010 03:10 AM

do it inside awk

Code:

echo "$STR" | awk '{for(i=3;i<=13;i+=2) print $i}'
there, short and sweet.

bashprog 09-28-2010 10:44 AM

That works, thanks. However I want to know why my code is not working. Also, since I am interested in extracting values from STR and using them as part of larger string , I want to use an outer loop. Can this be done ?

grail 09-28-2010 08:34 PM

I'll answer your question with a question, who's variable is $val in the following line:
Code:

v1=`echo $STR | awk '{print $val;}'`
By who I mean awk or bash? If you answer this you will have your answer, at least in part.

I will also assume that you were just using the echoes to check the data but are aware that the extra val variable is not required. At least
not if it is not to have any life past the awk.

Lastly, not understanding what the STR represents, have you thought of just putting it in an array and then using the appropriate indices? (ie no awk required at all)

bashprog 09-29-2010 01:18 AM

This is what I was looking for:
Code:

#!/bin/sh


STR='abcdef 0 1 1.3 2 2.5 3 3.6 4 4.9 5 5.7 6 6.3'

for i in 3 5 7 9 11 13

do

        echo i=$i
        v1=`echo $STR | awk '{print $'$i';}'`
        echo v1=$v1
done

To answer your questions:
val is not awk's variable. I explored using arrays and that worked too. Thanks for your help!

grail 09-29-2010 01:54 AM

I am sure your seq will still work too. Another small piece of advice which is less obvious in a small example like this
but may later be helpful. Try and use awk's variables to encompass the bash ones as later it will get confusing if you have many
variables to change in and out of quotes.

For example:
Code:

#!/bin/sh


STR='overt 0 1 1.3 2 2.5 3 3.6 4 4.9 5 5.7 6 6.3'

for i in 3 5 7 9 11 13

do

        echo i=$i
        v1=`echo $STR | awk -v var=$i '{print $var}'`
        echo v1=$v1
done



All times are GMT -5. The time now is 09:34 AM.