A safer way to extract the version number would be to interpret the field tag itself, rather than simply split by quotes.
$ sed -nr 'H;${;x;s/.*<field[^>]+name="cd_version"[^>]+defaultValue="([0-9.]+)"[^>]*\/>.*/\1/;p;}' input.txt
14.8.21.1
You can put the version in a variable using notation you're already familiar with:
$ v=$(sed -nr 'H;${;x;s/.*<field[^>]+name="cd_version"[^>]+defaultValue="([0-9.]+)"[^>]*\/>.*/\1/;p;}' input.txt)
$ echo $v
14.8.21.1
This sed script perhaps bears some explanation...
H;
- append the "current" line to sed's "hold space"
${;
- once we hit the last line, do the following...
x;
- eXchange the hold space for the pattern space (so we can work on it),
s/.*<field...([0-9.]+)...\/>.*/\1/;
- extract defaultValue
from the correct field,
p;}
- and print the result.
This should be safe for cases where multiple <field>
s appear on one line (as long as there's only one cd_version), or where the attributes of a <field>
are split over multiple lines.
Note that THIS IS A HACK, and you should probably be using tools which actually interpret fields like this correctly. It is widely thought that you cannot parse HTML with regex, and the same reasoning applies for other SGML.
Once you've got the version number, you can use sed -i
to replace it.
$ newver="foobar"
$ grep -o 'defaultValue="[^"]*"' input.txt
defaultValue="14.8.21.1"
$ sed -i '' 's/defaultValue="14.8.21.1"/defaultValue="'"${newver}"'"/' input.txt
$ grep -o 'defaultValue="[^"]*"' input.txt
defaultValue="foobar"
Note that I'm using FreeBSD, whose sed
may behave differently from the one in the operating system you're using. Even if this works, you should probably read the documentation for each tool and option used here to make sure you understand why it's doing what it's doing. In particular, the replacement regex I used was shortened for easier reading. To be safe, you should expand it in the same way it was expanded in the initial sed script which found the version number, so that you don't change defaultValue
for other fields besides cd_version
.