Reputation: 35
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.
Upvotes: 2
Views: 701
Reputation: 29266
You could let Awk do all the work. Awk does process line by line, so put the awk in a file and use awk -f your_program.awk
.
Something like this should work:
{
print "<item content=\"active\" type=\"\" fav=\"false\" mod=\"true\" index=\"0\">"
print "<number>"$1"</number>"
print "<number_type>sip</number_type>"
print "<first_name>"$2"</first_name>"
print "<last_name>"$3"</last_name>"
print "<organization>Stackoverflow</organization>"
print "</item>"
}
Upvotes: 3
Reputation: 14949
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
Upvotes: 4