csv到多个xml文件

时间:2015-08-12 20:18:40

标签: xml bash csv

我有一个csv文件,我需要一个bash脚本来转换多个xml文件中的行:

CSV文件示例

MAC Address, Extention, Account, Password
001122334455,Ext 200,5544332211,1122334455
554433221100,Ext 300,1122334455,5544332211

输出cfg001122334455.xml

<?xml version="1.0" encoding="UTF-8" ?>
<gs_provision version="1">
<mac>001122334455</mac>
  <config version="1">
<!--# Number: 0, 1-->
    <P271>1</P271>
<!--# Account Name//RAMAL -->
    <P270>Ext 200</P270>
<!--# SIP User ID-->
    <P35>5544332211</P35>
<!--# SIP Authenticate ID-->
    <P36>5544332211</P36>
<!--# SIP Authenticate Password-->
    <P34>1122334455</P34>
<!--# Display Name-->
    <P3>Ext 200</P3>
<!--# Accept Incoming SIP from Proxy Only-->
    <P2347>1</P2347>
<!--# Preferred Vocoder-->
    <P57>18</P57>
<!--# Remove OBP from Route-->
    <P2305>1</P2305>
<!--# Unregister On Reboot-->
    <P81>1</P81>
</config>
</gs_provision>

输出cfg554433221100.xml

<?xml version="1.0" encoding="UTF-8" ?>
<gs_provision version="1">
<mac>554433221100</mac>
  <config version="1">
<!--# Number: 0, 1-->
    <P271>1</P271>
<!--# Account Name//RAMAL -->
    <P270>Ext 300</P270>
<!--# SIP User ID-->
    <P35>1122334455</P35>
<!--# SIP Authenticate ID-->
    <P36>1122334455</P36>
<!--# SIP Authenticate Password-->
    <P34>5544332211</P34>
<!--# Display Name-->
    <P3>Ext 300</P3>
<!--# Accept Incoming SIP from Proxy Only-->
    <P2347>1</P2347>
<!--# Preferred Vocoder-->
    <P57>18</P57>
<!--# Remove OBP from Route-->
    <P2305>1</P2305>
<!--# Unregister On Reboot-->
    <P81>1</P81>
</config>
</gs_provision>

我尝试了一些awk命令,但没有成功。

1 个答案:

答案 0 :(得分:0)

我会使用printf模板:

template=$(cat <<'END_OF_XML'
<?xml version="1.0" encoding="UTF-8" ?>
<gs_provision version="1">
<mac>%s</mac>
  <config version="1">
<!--# Number: 0, 1-->
    <P271>1</P271>
<!--# Account Name//RAMAL -->
    <P270>%s</P270>
<!--# SIP User ID-->
    <P35>%s</P35>
<!--# SIP Authenticate ID-->
    <P36>%s</P36>
<!--# SIP Authenticate Password-->
    <P34>%s</P34>
<!--# Display Name-->
    <P3>%s</P3>
<!--# Accept Incoming SIP from Proxy Only-->
    <P2347>1</P2347>
<!--# Preferred Vocoder-->
    <P57>18</P57>
<!--# Remove OBP from Route-->
    <P2305>1</P2305>
<!--# Unregister On Reboot-->
    <P81>1</P81>
</config>
</gs_provision>
END_OF_XML
)

while IFS=, read -r mac ext acct pass; do
    printf "$template" "$mac" "$ext" "$acct" "$acct" "$pass" "$ext" > "cfg${mac}.xml"
done < "$1"