0

hi can some one please help me here i am trying to replace value in tomcat server.xml file username using sed command

<Resource username="user1" password="xxxxxxxx"/> 

below command replacing value as expected but missing "" around value as i am taking value from variable U.

export U="userx" sed -i -E 's/(username=)([a-zA-Z0-9"-])+/\1'"$U"'/g' server.xml 

output missing "" around userx : <Resource username=userx password="xxxxxxxx"/>

if i use value instead of variable its working with "" as well

sed -i -E 's/(username=)([a-zA-Z0-9"-])+/\1"userx"/g' server.xml ouput: <Resource username="userx" password="xxxxxxxx"/> 

    1 Answer 1

    1

    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' 
    1
    • thanks for your help, yes it's working fine and much easier the sed command, as I have multiple xml files to edit, and this suits to fix all my issues :). thanks once again for quick help
      – rajesh
      CommentedFeb 13, 2022 at 11:57

    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.