问题
I have been tasked to write a script to change a specific value in an XML file on about 1000 Macs. Clearly this needs to be scripted, and preferably only using tools that are already available on a Mac (i.e. no additional installs needed). The end goal here is to disable IPv6 in a specific file related to active directory. For example:
Old file:
<IPv4>
<script>Automatic</script>
</IPv4>
<IPv6>
<script>Automatic</script>
</IPv6>
New file:
<IPv4>
<script>Automatic</script>
</IPv4>
<IPv6>
<script>__INACTIVE__</script>
</IPv6>
I have tried searching and have a few sed scripts that get me halfway there, but no where close enough. I can't install any XML parsing programs as this needs to be as automated as possible on all the Macs.
Edit: secondary question-
using either awk or sed, can I count the number of times that it made a change, i.e. counting the number of instances it found?
回答1:
Using awk:
awk '/<IPv6>/,/<\/IPv6>/ {sub(/Automatic/,"__INACTIVE__")}1' xml_file > new_xml_file
Using sed: In-line editing
sed -i '/<IPv6>/,/<\/IPv6>/s/Automatic/__INACTIVE__/' xml_file
To add counts in the mix:
awk '
/<IPv6>/,/<\/IPv6>/ {sub(/Automatic/,"__INACTIVE__"); if ($0~/__/) count++}1
END{ print FILENAME, count >>"countfile"}' xml_file> new_xml_file
The END statement will capture the Filename you ran the script on and the counts of changes in a file called countfile and will keep appending to it for your statistical analysis.
来源:https://stackoverflow.com/questions/8514985/how-to-change-specific-value-of-xml-attribute-using-scripting-on-mac