如何复制源XML文件,并在输出中向预定义属性添加累进数?
我有一个包含一系列组的XML文件,例如如何复制源XML文件,并在输出中向预定义属性添加累进数?,xml,regex,bash,shell,Xml,Regex,Bash,Shell,我有一个包含一系列组的XML文件,例如 <Group id="CB1391262521L-10816-1390650339-936236343" name="This Speed" color="#FFFFFF"> <Topology> <TopologyRect cylinderHor="false" hcount="1" cylinderVert="false" vcount="1"/
<Group id="CB1391262521L-10816-1390650339-936236343" name="This Speed" color="#FFFFFF">
<Topology>
<TopologyRect cylinderHor="false" hcount="1" cylinderVert="false" vcount="1"/>
</Topology>
<Name="test">
<Parameter value="1" name="ssd"/>
<Parameter value="1" name="amp"/>
</Name>
<Note></Note>
<DiagramIcon width="50" x="89" y="392" height="50"/>
</Group>
<Group id="L-14827-1391619839-708665346" name="Angle" color="#FFFFFF">
<Topology>
<TopologyRect cylinderHor="false" hcount="1" cylinderVert="false" vcount="2"/>
</Topology>
<Name="test">
<Parameter value="3" name="ssd"/>
<Parameter value="2" name="amp"/>
</Name>
<Note></Note>
<DiagramIcon width="50" x="89" y="392" height="50"/>
</Group>
其中5是副本数,脚本的输出将生成5.xml文件,其中第一个文件的id、目标和源属性中包含的所有值都是-01,第二个文件的id、目标和源属性中包含的值都是-02等等
我认为这是一个正则表达式搜索和替换,不需要用Python解析原始XML文件,只需将其作为普通文本文件逐行读取即可。Pure shell
#!/usr/bin/env bash
xml=$1
n=$2
for i in $(seq $n)
do
i=$(printf "%02s" $i)
sed -r "s/((id|target|source)=\"[^\"]+[0-9])/\1-$i/g" $xml > $i.xml
done
如何运行
然后您将得到5个xml文件:01.xml、02.xml等。
Python解决方案:
import re
n=5
with open("source.xml","r") as source:
xml = source.read()
for i in range(n):
with open("out-%d.xml" % i,"w") as target:
modxml = re.sub(r'(id|target|source)="([^"]*)"',r'\1="\2-%d"' % i,xml)
target.write(modxml)
您需要专门使用python的代码吗?这也可以使用unix工具实现。当然,不一定是python。使用grep和for循环的unixshell脚本就可以了。如果是这种情况,我将更改问题的标题,以便使其反映答案。它有效,谢谢。我注释了
I=$(printf“%02s”$I)
因为我在后缀之前不需要空格(例如id=“475839”->id=“475839-1”而不是id=“475839-1”),我更新了sed命令,现在它可以处理空格问题了。如果需要前导零,仍然可以保留printf
命令。
#!/usr/bin/env bash
xml=$1
n=$2
for i in $(seq $n)
do
i=$(printf "%02s" $i)
sed -r "s/((id|target|source)=\"[^\"]+[0-9])/\1-$i/g" $xml > $i.xml
done
myScript.sh OriginalFile.xml 5
import re
n=5
with open("source.xml","r") as source:
xml = source.read()
for i in range(n):
with open("out-%d.xml" % i,"w") as target:
modxml = re.sub(r'(id|target|source)="([^"]*)"',r'\1="\2-%d"' % i,xml)
target.write(modxml)