1

I am trying to replace string within quotes in a file! Here is an example :

<?xml version="1.0" encoding="UTF-8"?> <Context> <Manager pathname="" /> <Resource auth="Container" driverClassName="org.postgresql.Driver" maxActive="20" maxIdle="5" maxWait="10000" name="jdbc/custom" password="CHANGEIT" type="javax.sql.DataSource" url="jdbc:postgresql://10.10.10.10:5432/database" username="MyUser"/> </Context> 

This command works for several 'fields' but it doesn't work with username because of / .

# It's OK sed 's/\(.*password=\)[^ ]*\( .*\)/\1"NEW_VALUE"\2/' ROOT.xml # It's NOK sed 's/\(.*username=\)[^ ]*\( .*\)/\1"NEW_VALUE"\2/' ROOT.xml 

How can I do that please ?

Thank you,

3 Answers 3

0

You have to change the command

sed 's/\(.*username=\)[^ ]*\( .*\)/\1"NEW_VALUE"\2/' ROOT.xml 

into

sed 's/\(.*username=\)[^ \/]*\( .*\)/\1"NEW_VALUE"\2/' ROOT.xml 

because [^ ] means: Every character except a blank. [^ \/] means: Every character except a blank and/or /.

6
  • Thanks... but it doesn't work for me :( Commented Feb 15, 2017 at 9:50
  • What do you get, if you run my adjusted command on the text in your initial question? Commented Feb 15, 2017 at 10:06
  • I've got this : [root@mymachine ~]# sed 's/(.*username=)[^ \/]*( .*)/\1"NEW_VALUE"\2/' ROOT.xml <?xml version="1.0" encoding="UTF-8"?> <Context> <Manager pathname="" /> <Resource auth="Container" driverClassName="org.postgresql.Driver" maxActive="20" maxIdle="5" maxWait="10000" name="jdbc/custom" password="CHANGEIT" type="javax.sql.DataSource" url="jdbc:postgresql://10.10.10.10:5432/database" username="MyUser"/> </Context> No changes made Commented Feb 15, 2017 at 11:51
  • Why are you calling sed with (.*username=) instead of \(.*username=\) and ( .*) instead of \( .*\) ? Look here: grymoire.com/Unix/Regular.html#uh-10 Commented Feb 15, 2017 at 12:20
  • Look at your command: sed 's/(.*username=)[^ \/]*( .*)/\1"NEW_VALUE"\2/' ROOT.xml. Then look at my comment. Commented Feb 15, 2017 at 13:16
0

Change to this:

sed 's/\( username="\)[^"]*/\1NEW_VALUE/' ROOT.xml

It will get any pattern with a space + username + double quotation until the next double quotation and change for the first part and the new value.

0

To fix this, you can change the delimiter in the sed command from / to another character that doesn't appear in your XML content, such as |. Here's how you can modify your sed command to handle this:

sed 's|\(.*username=\)[^ ]*\(\s.*\)|\1"NEW_VALUE"\2|' ROOT.xml 

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.