Sed Multiple Patterns Matching And Replace

Shell Scripting

Sed is a beautiful tool for text replacements and extraction using regex and pattern matching.

While working on a project we had to replace a unknown string in a xml file only when it matches multiple patterns. I checked through google and found some nice hints but could not able to get the exact what we were trying to achieve.

Below are few examples which will help those who are in need of a sed command to replace a pattern in a file

Matching multiple patterns and replacing a unknown string with a new value.:

A xml file contains below contents and we need to replace the highlighted string(something unknown) with some new value only after pattern matching.

Build.xml:

<property name="db.host" value="localhost"/>

<property name="db.port" value="1574"/>

<property name="db.sid" value="my11gdb"/>

sed -ie 's/\(<property name=\"db\.sid\" value=\"\)\(.*\)\(\"\/>\)/\1NEWSID\3/g' build.xml

sed -ie 's/\(<property name=\"db\.host\" value=\"\)\(.*\)\(\"\/>\)/\1NEWHOSTNAME\3/g' build.xml

sed -ie 's/\(<property name=\"db\.port\" value=\"\)\(.*\)\(\"\/>\)/\1NEWPORT\3/g' build.xml

Here in above example you can see we have divided the patterns to 3 different sections, like (Fixed section)(Variable/Unknown Section)(Fixed Section) which are accessed by 1,2,3. By dividing it into sections which makes it very easy to replace.

Similarly if we want to match multiple patterns and replace we can break it into more sections using () and make it more secure replaces . See below example where we will be matching multiple patterns before replacing the text.

Build.xml:

<custom:dbConfig series="local_codeline11.k.8.12.77.0_fx" host="localhost" port="1574" sid="my11gdb" user="fusion_runtime" pass="fusion_runtime"/>

So here we will try to multiple match and replace host, port and sid values. We can achieve this by breaking the line into 4parts like below:

sed -ie 's/\(<custom\:dbConfig.*\)\( host=\"\)\(.*\)\(\" port=\)/\1\2NEWHOSTNAME\4/g' build.xml

sed -ie 's/\(<custom\:dbConfig.*\)\( port=\"\)\(.*\)\(\" sid=\"\)/\1\2NEWPORT\4/g' build.xml

sed -ie 's/\(<custom\:dbConfig.*\)\( sid=\"\)\(.*\)\(\" user=\"\)/\1\2NEWSID\4/g' build.xml

Here we wanted to replace the 3rd part with the new string.Here we want to keep 1,2,4 parts same and willing to change the 3rd part so the 3rd part is changed to new string in above command.

In case of any ©Copyright or missing credits issue please check CopyRights page for faster resolutions.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.