tags:

views:

46

answers:

3

hi all

the following program needs to print the words

First 

Second 

Third

But because i parameter from awk not get the value from “for” loop its print all words:

     First second third
     First second third
     First second third

How to fix awk in order to print first the “first” word second the “second” word and so on

THX

Yael

 program:

 for i in 1 2 3
 do
 echo "first second third" | awk '{print $i}'
 done
+1  A: 

You can change you code like this:

for i in 1 2 3
do
 echo "first second third" | awk -v i=$i '{print $i}'
done

To use the variable 'i' from the shell.

You can also just change the record separator (RS) to have the same result :

echo "first second third" | awk 'BEGIN{RS=" "} {print $1}'

But I'm not sure if that's what you're looking for.

Aissen
It's better not to use the quote-unquote-quote method because it's hard to read. This, which uses awk's variable passing, is better: `awk -v i=$i '{print $i}'`
Dennis Williamson
You are definitely right `echo "first second third" | awk '{print $'${i}'}'` was not a good solution. So I edited the answer to follow your method.
Aissen
+1  A: 

You could do:

for a in First Second Third
do
    awk 'BEGIN { print ARGV[1] }' $a
done

Or you could do:

for a in First Second Third
do
    awk -v arg=$a 'BEGIN { print arg }'
done
JUST MY correct OPINION
+1 for suggesting `-v`
glenn jackman
+1  A: 

don't do the unnecessary. the shell for loop is not needed! Just do it with awk!

$ echo "first second third" | awk '{for(i=1;i<=NF;i++)print $i}'

ghostdog74