我正尝试使用awk如下生成xml。输入文件:
10.112.232.34|bl|1
10.23.435.21|bl|1
34.4532.32.1|bl|0
预期的输出应该像
<Update version="1">
<BlackListed_IP>
<Added>
<value IP="180.104.243.1" CODE="BL"></value>
<value IP="180.104.243.1" CODE="BL"></value>
</Added>
<Deleted>
<value IP="180.104.243.1" CODE="BL"></value>
</Deleted>
</BlackListed_IP>
下面是我用来获得预期输出的内容。
function prepere_xml{
while IFS='' read -r line || [[ -n "$line" ]];
do
while IFS='|' read f1 f2 f3
if [ "$f3" == 1 ]; then
awk -v c="$line" -F\| 'BEGIN{printf "<Update version=\"%s\">\n <BlackListed_IP>\n <Added>\n", c} {printf " <value IP=\"%s\" CODE=\"%s\"></value>\n", $1, $2} END {printf " </Added>\n </BlackListed_IP>\n</Update>"}' $collect_sid_msg > Generated_Delta.xml
else
awk -v c="$line" -F\| 'BEGIN{printf " <Deleted>\n", c} {printf " <value IP=\"%s\" CODE=\"%s\"></value>\n", $1, $2} END {printf " </Deleted>\n</Update>"}' $collect_sid_msg >> Generated_Delta.xml
fi
done<$input_file
done < $update_version
}
update_version.txt文件所在的
1
答案 0 :(得分:2)
$ cat tst.awk
BEGIN { FS="[|]" }
$3 == 1 { addedIp[++numAdded]=$1; addedCode[numAdded]=$2; next }
{ deletedIp[++numDeleted]=$1; deletedCode[numDeleted]=$2 }
END {
printf "<Update version=\"%d\">\n", update_version
print " <Blacklisted_IP>"
print " <Added>"
for (i=1; i<=numAdded; i++) {
printf " <value> IP=\"%s\" CODE=\"%s\"></value>\n", addedIp[i], toupper(addedCode[i])
}
print " </Added>"
print " <Deleted>"
for (i=1; i<=numDeleted; i++) {
printf " <value> IP=\"%s\" CODE=\"%s\"></value>\n", deletedIp[i], toupper(deletedCode[i])
}
print " </Deleted>"
print " </Blacklisted_IP>"
}
$ awk -v update_version=1 -f tst.awk file
<Update version="1">
<Blacklisted_IP>
<Added>
<value> IP="10.112.232.34" CODE="BL"></value>
<value> IP="10.23.435.21" CODE="BL"></value>
</Added>
<Deleted>
<value> IP="34.4532.32.1" CODE="BL"></value>
</Deleted>
</Blacklisted_IP>