我使用以下代码提取数据文件并尝试使用附加到现有的xml标记 sed但它没有返回a,b和c的值。
while read -r a b c ; do
cat xml | sed '\|<entry>| a <test_id>${a}</test_id> ' >> xml_out.xml
cat xml | sed '\|<entry>| a <test_case>${b}</test_case> ' >>xml_out.xml
cat xml | sed '\|<entry>| a <region>${c}</region> ' >>xml_out.xml
done < input_data.dat
a) Input data(input_data.dat)
12123 'QA test case 1' 'QA environment'
12234 'UAT test case 1' 'UAT environment'
b)xml(输入文件 2014-05-28T19:10:00-07:00 1000573988
<entry>
<updated>2014-05-28T19:10:00-07:00</updated>
<id>1000573988</id>
</entry>
Expected output(xml_out.xml)
(after append xml file)
<entry>
<test_id>12123</test_id>
<test_case>QA test case 1</test_case>
<region>QA environment</region>
<updated>2014-05-28T19:10:00-07:00</updated>
<id>1000573988</id>
</entry>
<entry>
<test_id>12234</test_id>
<test_case>UAT test case 1</test_case>
<region>UAT environment</region>
<updated>2014-05-28T19:10:00-07:00</updated>
<id>1000573988</id>
</entry>
答案 0 :(得分:1)
如果您的输入数据字段以逗号分隔(如您显示的第二行),并且除此之外没有逗号,您可以执行以下操作:
IFS=, # set the input field separator to a comma
while read -r a b c ; do
b=${b//\'/} # remove the single quotes from the string
c=${c//\'/} # ditto
sed '\|<entry>| a <test_id>${a}</test_id> ' xml >> xml_out.xml
sed '\|<entry>| a <test_case>${b}</test_case> ' xml >>xml_out.xml
sed '\|<entry>| a <region>${c}</region> ' xml >>xml_out.xml
done < input_data.dat
答案 1 :(得分:0)
我的猜测就是这就是真正想要的东西:
IFS=','
while read -r a b c ; do
b=${b//\'/}
c=${c//\'/}
sed '\|<entry>| a \
'"<test_id>${a}</test_id>\\
<test_case>${b}</test_case>\\
<region>${c}</region>" xml
done > xml_out.xml << _EOF_
12123,'QA test case 1','QA environment'
12234,'UAT test case 1','UAT environment'
_EOF_
cat xml_out.xml
好吧,当我运行它时:
$ cat sh.sh ; echo ;bash ./sh.sh
# set -x
IFS=','
while read -r a b c ; do
b=${b//\'/}
c=${c//\'/}
sed '\|<entry>| a \
'"<test_id>${a}</test_id>\\
<test_case>${b}</test_case>\\
<region>${c}</region>" xml
done > xml_out.xml <<- _EOF_
12123,'QA test case 1','QA environment'
12234,'UAT test case 1','UAT environment'
_EOF_
cat xml_out.xml
<entry>
<test_id>12123</test_id>
<test_case>QA test case 1</test_case>
<region>QA environment </region>
<test>QA test case 1</test>
<updated>2014-05-28T19:10:00-07:00</updated>
<id>1000573988</id>
</entry>
<entry>
<test_id>12234</test_id>
<test_case>UAT test case 1</test_case>
<region>UAT environment</region>
<test>QA test case 1</test>
<updated>2014-05-28T19:10:00-07:00</updated>
<id>1000573988</id>
</entry>
还有待抛光,但这确实是“读者的练习”。