Awk + awk export value

the next program should print the words

First 

Second 

Third

But since the parameter i from awk does not get the value from the "for" loop, it prints all the words:

     First second third
     First second third
     First second third

How to fix awk to first type the "first" word, "second" word, etc.

THX

Yael

 program:

 for i in 1 2 3
 do
 echo "first second third" | awk '{print $i}'
 done
+3
source share
4 answers

You can change your code as follows:

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

Use the variable 'i' from the shell.

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

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

But I'm not sure if this is what you are looking for.

+2
source

You can 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
+2
source

do not do unnecessary. a shell for the loop is not needed! Just do it with awk!

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

+2
source

Or you could use:

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

Source: https://habr.com/ru/post/1753146/


All Articles