Saintmrdog
Saintmrdog

Reputation: 13

Passing two awk columns into a while read command

SampleFile:

Two Words,Extra

My code:

cat SampleFile | awk -F "," '{print $1" "$2}' | while read var1 var2;
do
    echo $var1
done

This will print out only Two and var2 will take Words. Is there a way so that I can pass Two Words into var1?

Upvotes: 0

Views: 565

Answers (2)

Benjamin W.
Benjamin W.

Reputation: 52381

You don't have to use awk for this. Bash has a built-in variable to determine where words are split:

while IFS=, read -r var1 var2; do
    echo "$var1"
done < SampleFile

IFS is set to ,, so word splitting takes place at commas.

Instead of piping to the while loop, I use redirection, which has the advantage of not spawning a subshell.


A remark: you don't need cat in this context. Awk can take a file name as an argument, so

cat SampleFile | awk -F "," '{print $1" "$2}'

becomes

awk -F "," '{print $1, $2}' SampleFile

Also, when using print, you don't need to explicitly introduce spaces: if you comma-separate your fields, awk will replace the comma by the value of the OFS (output field separator) variable, which defaults to a space.

Upvotes: 3

Ali ISSA
Ali ISSA

Reputation: 408

...| while read var1; do echo $var1 done

Upvotes: 0

Related Questions