Reputation: 1304
To change the Tomcat password in the following line
<user username="user1" password="tomcat" roles="tomcat"/>
I'm trying
sed -i s/'username=\"user1\" password=\".*\"'/'username=\"user1\" password=\"NEWPASS\"'/g tomcat-users.xml
but the resulting line will be
<user username="user1" password="NEWPASS"/>
How do I change the regular expression to not cut off the last attribute? I want it to look like
<user username="user1" password="NEWPASS" roles="tomcat"/>
Upvotes: 1
Views: 205
Reputation: 51
Less is more. Replace the g with a 1
sed -i s/tomcat/NEWPASS/1 tomcat-users.xml
Upvotes: 0
Reputation: 33319
Try the following substitution:
sed -i 's/password="[^"]*"/password="NEWPASS"/' tomcat-users.xml
If you want to do the substitution only in the line corresponding to user1, specify a regexp address:
sed -i '/username="user1"/ s/password="[^"]*"/password="NEWPASS"/' tomcat-users.xml
Explanation:
# for lines that match
# this regexp...
# ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
'/username="user1"/ s/password="[^"]*"/password="NEWPASS"/'
# ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
# ...execute this command.
Upvotes: 2
Reputation: 3370
Presumably, you only want to do this for lines that contain username="user1"
. So, you could do
sed -i '/username="user1"/{s/password="[^"]*"/password="NEWPASS"/}
The idea is to find any lines that contain username="user1"
and run the script only on those. This is achieved by the /foo/{...}
syntax. Then, you identify the password by looking for the longest stretch of non-"
after password="
and replace the whole thing with the new version.
There is no need for g
, that makes sed replace all occurrences in any single line ans is unnecessary here.
Upvotes: 0
Reputation: 174696
You could try the below sed command,
$ sed 's~\(<user username="user1" password="\)[^"]*~\1NEWPASS~g' file
<user username="user1" password="NEWPASS" roles="tomcat"/>
Upvotes: 1