[英]Parse multiple awk variables in a “for” loop bash
我试图将多个awk变量解析为for循环。 我有一个文档,其中包含多个用逗号分隔的字段。 每个字段都由awk捕获,我想使用这些变量在其他文件中创建多个文本实例。 我使用了“ while”来捕获变量,但是只能运行一次。
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
test.txt的输出为:
<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>
如果使用for循环,它将不会单独保留3个变量,而是将合并后的输出放入一个变量中。
您不需要使用awk
。 您可以使用IFS
(内部字段分隔符)使用bash
本身来完成此操作。
用这个:
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
您可以让Awk完成所有工作。 Awk逐行处理,因此将awk放在文件中并使用awk -f your_program.awk
。
这样的事情应该起作用:
{
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>"
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.