I'm interested in finding out what's the shortest script one can write to replace one XML element in a file with another one from a second file.
I can whip up a simple program to easily do this, but I'm wondering if it's easily do-able using a shell script. It's just a utility tool meant开发者_开发问答 as a convenience. Can this be done using sed
? awk
? I'm not familiar with those. I suppose I can probably do it with a combination of grep
and wc
, but it seems likely that there's a much more direct way to do this.
Essentially, I have a large configuration file, say config.xml
, which say looks like this:
<config>
<element name="a">
<subelement />
</element>
<element name="b">
<subelement />
</element>
<element name="c">
<subelement />
</element>
<!-- and so on... -->
</config>
Once in a while, changes require me to modify/add/delete one subelement
. Now, it so happens that there's a sort of generator that will generate an up-to-date subconfig.xml
, like following file:
<config>
<element name="c">
<subelement />
<subelement />
</element>
</config>
My thinking is that if I can take the element
in subconfig.xml
and replace the existing one in config.xml
, then hey, that'd be great! Yea, it's not much a work-saver, since it's only needed rarely, but it just occurred to me that I could try to do it in a script, but I'm not sure how.
Any help appreciated (including pointing out that I'd be better off writing a program for this ^-^).
If your xml are consistent and your replacement requirement is simple, there's actually no need to use parsers. Just simple awk will do
$ subconfig=(<subconfig.xml)
$ awk -v subconf=$subconfig '/<config>/{print subconf}/<config>/,/<\/config>/{next}1' config.xml
I wouldn't attempt to do this with command-line tools, you'll run into all sorts of difficulties. The way you should do this is with a proper XML parser. The logic would be: consume original file, parse it, consume update file, parse it, identify which node this guy is to replace, do the replace, write out the result.
I don't know what you are comfortable with coding-wise, but there's XML parsers available in most popular languages.
精彩评论