Editing XML with sed
can be prone to failure. Use an XML editing tool instead. For example, with xmlstarlet
it becomes trivial
U='userx' xmlstarlet edit --inplace --update '//Resource/@username' --value "$U" server.xml
Personally, I wouldn't use --inplace
until I'd finished testing that the replacement worked.
xmlstarlet
is commonly available from your distribution's package manager. If you don't have it and don't have the rights to install it, submit a request to your Change Board to do so. It's about using the right tool for the right job.
Incidentally, the reason your sed
command didn't work is because it never saw the double quotes you wanted to include. Here's your original command with some annotation
sed -E 's/(username=)([a-zA-Z0-9"-])+/\1'"$U"'/g' ^single quotes start ^single quotes end ^double quotes start ^double quotes end
The shell uses quotes to identify how to parse strings (or not). The single quotes provide a literal sequence of characters. Double quotes protect most characters but specifically allow variables to be evaluated. The command (sed
in this instance) never sees these outer quotes. So to include double quotes in your string you need to quote them.
For readability but not syntactic accuracy I have split the corrected single expression at quotes
sed -E 's/(username=")([a-zA-Z0-9-])+/\1' "$U" '"/g' ^literal text used as an RE ^variable (quoted to protect it from the shell) ^more literal text
Putting this together again so that sed
sees a single expression string,
sed -E 's/(username=")([a-zA-Z0-9-])+/\1'"$U"'"/g'