Vituvo
Vituvo

Reputation: 1048

How to change a word on a line that has a certain string on it

Ubuntu 16.04

I have a xml file that has about 50 lines of code. There is a certain line that contains the string "FFFedrs". ON this line is the word true.

If the structure was neat with only 1 space between like so .. <property name="FFFedrs" value="true"/> <!-- Enables/Disables EasyMoney -->

I could use a sed in place command like this:

$ cat file.xml

<property name="FFFedrs" value="true"/> <!-- Enables/Disables EasyMoney -->

$ sed -i 's/<property\ name=\"FFFedrs\"\ value=\"true\"\/>\ <!--\ Enables\/Disables\ EasyMoney\ -->/<property\ name=\"FFFedrs\"\ value=\"false\"\/>\ <!--\ Enables\/Disables\ EasyMoney\ -->/g' file.xml
$
$ cat file.xml

<property name="FFFedrs" value="false"/> <!-- Enables/Disables EasyMoney -->

But the file is not neatly formatted so the line that has the string "FFFedrs" looks something like ...

 <property name="FFFedrs"              value="true"/>       <!-- Enables/Disables EasyMoney -->

How do I sed the true to false on the line that has the string "FFFedrs"

Upvotes: 0

Views: 61

Answers (2)

David Peltier
David Peltier

Reputation: 91

This should do the trick

sed -i 's|\(<.*FFFedrs"\)\s*\(value.*>\)\s*\(<.*>\)|\1 \2 \3|' file

I use a pipe in sed as a separator because your line has slashes in. 3 groups of capture for the main values and output as wanted

You can use https://regex101.com/ to learn about regex and test it live.

Upvotes: 0

Andriy Makukha
Andriy Makukha

Reputation: 8314

Just add \+ after your spaces:

sed -i 's/<property\ \+name=\"FFFedrs\"\ \+value=\"true\"\/>/<property\ name=\"FFFedrs\"\ value=\"false\"\/>/g' file.xml

This will replaces multiple spaces with a single space.

If you want to preserve the spaces:

sed -i 's/<property\(\ \+\)name=\"FFFedrs\"\(\ \+\)value=\"true\"\/>/<property\1name=\"FFFedrs\"\2value=\"false\"\/>/g' file.xml

Upvotes: 1

Related Questions