gogasca
gogasca

Reputation: 10058

Using sed to replace xml attribute

My file contains a line like this:

<virtual-server name="default-host" enable-welcome-root="false">

I want to replace: enable-welcome-root from false to true

Using sed -n 's/.*enable-welcome-root="\([^"]*\).*/\1/p' file I can get the value which is false, but how can I replace it?

Upvotes: 3

Views: 7679

Answers (3)

glenn jackman
glenn jackman

Reputation: 246774

Using xmlstarlet, and adding a close tag to your line:

xmlstarlet ed -O -u '//virtual-server/@enable-welcome-root[.="false"]' -v "true" <<END
<virtual-server name="default-host" enable-welcome-root="false">
</virtual-server>
END
<virtual-server name="default-host" enable-welcome-root="true">
</virtual-server>

Upvotes: 3

Cyrus
Cyrus

Reputation: 88583

Your string contains no special characters. Thus:

s='<virtual-server name="default-host" enable-welcome-root="false">'
r='<virtual-server name="default-host" enable-welcome-root="true">'
sed -i -e "s/$s/$r/" file

Upvotes: 3

Jotne
Jotne

Reputation: 41456

This would change from false or true to true

sed -r 's/(enable-welcome-root=")[^"]+"/\1true"/' file
<virtual-server name="default-host" enable-welcome-root="true">

or without -r

sed 's/\(enable-welcome-root="\)[^"]+"/\1true"/'
<virtual-server name="default-host" enable-welcome-root="false">

Use -i to write back to file

Upvotes: 5

Related Questions