Jose Torres Jose Torres - 26 days ago 11
Linux Question

shell script sed replace

I have this file config.xml

<widget id="com.example.hello" version="0.0.1">
<name>HelloWorld</name>
<description>
A sample Apache Cordova application that responds to the deviceready event.
</description>
<author email="dev@callback.apache.org" href="http://cordova.io">
Apache Cordova Team
</author>
<enter>PASSWORD</enter>
<content src="index.html" />
<access origin="*" />




I tried to do it with sed without success.

I need to do this:

$./script.sh config.xml NEWPASSWORD


to get:

<widget id="com.example.hello" version="0.0.1">
<name>HelloWorld</name>
<description>
A sample Apache Cordova application that responds to the deviceready event.
</description>
<author email="dev@callback.apache.org" href="http://cordova.io">
Apache Cordova Team
</author>
<enter>NEWPASSWORD</enter>
<content src="index.html" />
<access origin="*" />



Answer

Using backreference:

sed "s/^\( *<enter>\)\([^>]*\)</\1$2</" "$1"
  • ^\( *<enter>\): search for lines starting with any number of spaces followed by <enter>. Matching characters are captured with escaped parentheses.

  • \([^>]*\)<: following characters up top next < are captured in a second group.

  • \1$2<: in the substitution string, characters from first group are output(\1) followed by the second parameter value passed to the script, ($2, the new password value)

The command is applied to $1, the file passed as first parameter to the script (the file name).

To edit the file in place, use the -i flag:

sed -i "s/^\( *<enter>\)\([^>]*\)</\1$2</" "$1"