开发者

awk + export value to awk

the following program needs to print the words

First 

Second 

Third

But because i parameter from awk n开发者_开发问答ot 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


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.


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


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}'


Or you could use:

echo "first second third" | awk -F " " -v OFS="\n"  '{print $1,$2,$3}'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜