This looks remarkably like an XML file. It is strongly recommended to use XML-related tools for this job such as xmlstarlet
.
Assuming a given input file of the form :
<header>
<node>
<key>UniqueKey</key>
<foo />
<string>100</string>
</node>
<node>
<key>UniqueKey</key>
<string>101</string>
<string>200</string>
</node>
</header>
Then the following command will update as requested :
$ xmlstarlet ed -u '//key[text()="UniqueKey"]/following-sibling::string[1]' \
-x '(text()+1)' file.xml
This does the following :
The output is then given by :
<?xml version="1.0"?>
<header>
<node>
<key>UniqueKey</key>
<foo/>
<string>101</string> # change
</node>
<node>
<key>UniqueKey</key>
<string>102</string> # change
<string>200</string> # no change
</node>
</header>
Or if it realy has to be the next node, then you need to play a trick with concat
and substring
as xpath-1.0 does not have if conditions. More details here
$ xmlstarlet ed -u '//key[text()="UniqueKey"]/following-sibling::*[1]' \
-x 'substring(text()+1,1,number(name()="string")*string-length(text()+1))' file.xml
<?xml version="1.0"?>
<header>
<node>
<key>UniqueKey</key>
<foo/>
<string>100</string> # no change
</node>
<node>
<key>UniqueKey</key>
<string>102</string> # change
<string>200</string> # no change
</node>
</header>