Dalton90 Dalton90 - 5 months ago 16
Bash Question

Parse multiple awk variables in a "for" loop bash

I am trying to parse multiple awk variables into a for loop. I have a document that consists of multiple fields separated by a comma. Each field is capture by awk and I want to use these variables to create multiple instances of text in an additional file. I have used "while" to capture the variables, but this only runs once.

awk -F ',' '{print $1,$2,$3}' extensions.txt | while read var1 var2 var3; do
echo " <item context=\"active\" type=\"\" fav=\"false\" mod=\"true\" index=\"0\">
<number>$var3</number>
<number_type>sip</number_type>
<first_name>$var1</first_name>
<last_name>$var2</last_name>
<organization>Stackoverflow</organization>
</item>" > test.txt
done
exit


Output for test.txt is:

<item context=\"active\" type=\"\" fav=\"false\" mod=\"true\" index=\"0\">
<number>123456789</number>
<number_type>sip</number_type>
<first_name>Jon</first_name>
<last_name>Doe</last_name>
<organization>Stackoverflow</organization>
</item>


If I use a for loop, it won't retain the 3 variables seperately, but rather take the combined output and place it into a single variable.

sat sat
Answer

You don't need to use awk. You can do it with bash itself by using IFS (Internal Field Separator).

Use this:

while IFS="," read v1 v2 v3
do
    echo "<item context=\"active\" type=\"\" fav=\"false\" mod=\"true\" index=\"0\">
    <number>$v1</number>
    <number_type>sip</number_type>
    <first_name>$v2</first_name>
    <last_name>$v3</last_name>
    <organization>Stackoverflow</organization>
    </item>";
done < extensions.txt > output.txt