Was hoping someone can assist;
I've got an xml file where I want to search for a specific string and then replace with different text each time a match is found. For example I need to search for everything with machine tags within xml the file so the results look similar to;
...
<machine>devbox1.mydomain.com</machine>
...
<machine>devbox2.mydomain.com</machine>
...
<machine>devbox1.mydomain.com</machine>
...
<machine>devbox2.mydomain.com</machine>
...
<machine>devbox1.mydomain.com</machine>
...
...
I now have 4 new systems where I need to replace each occurrence of devbox* to end up something like;
...
<machine>newbox1.mydomain.com</machine>
...
<machine>newbox2.mydomain.com</machine>
...
<machine>newbox3.mydomain.com</machine>
...
<machine>newbox4.mydomain.com</machine>
...
<machine>newbox1.mydomain.com</machine>
...
...
I've made an initial attempt in the form of a bash script, by building a while loop to read each line and grep for the required string, but I'm not sure if this is the best way of doing it?
Any tips or pointers would be appreciated.
Thanks C
Assuming there cannot be more than one <machine>
tag per line (or at least not more than one of those to be replaced), this Python script should do the work:
#!/usr/bin/env python
import sys
import re
from itertools import cycle
regex = re.compile('^(.*<machine>)devbox\d+(\.mydomain\.com</machine>.*)$')
box = cycle([1, 2, 3, 4])
for l in sys.stdin:
m = regex.match(l)
if m:
l = m.group(1) + 'newbox' + str(next(box)) + m.group(2)
print(l)
Save it to a file (say newboxer.py
) and make executable, and then you can use:
> ./newboxer.py < input.xml > output.xml