0

I would like to substitute the values of XML attributes matching a regex in a file in bash.

 <Resource name="MailSession" auth="Container" type="javax.mail.Session"
            mail.smtp.host="localhost" mail.smtp.user="foo" mail.smtp.passwd="12345678"
            mail.pop3.host="localhost" mail.pop3.user="foo" mail.pop3.passwd="12345678"/>

should be transformed to

 <Resource name="MailSession" auth="Container" type="javax.mail.Session"
            mail.smtp.host="***" mail.smtp.user="foo" mail.smtp.passwd="***"
            mail.pop3.host="***" mail.pop3.user="foo" mail.pop3.passwd="***"/>

This should be possible using sed or awk.

1

3 Answers 3

4

I'd have my sed command like this:

sed -E 's@(mail[.][^.]+[.])(host|passwd)="[^"]*"@\1\2="***"@g' file

Output:

 <Resource name="MailSession" auth="Container" type="javax.mail.Session"
            mail.smtp.host="***" mail.smtp.user="foo" mail.smtp.passwd="***"
            mail.pop3.host="***" mail.pop3.user="foo" mail.pop3.passwd="***"/>

You can add -i option to sed to directly modify the file.

Sign up to request clarification or add additional context in comments.

Comments

1

If your XML file is called "test.xml" you can:

cat test.xml | sed 's/host="[^"]*/host="***/g' | sed 's/passwd="[^"]*/passwd="***/g'

If you are reading the file from other place (such as HTTP connection, or whatever) you can modify the first command of the pipe.

Comments

1

Using awk

 awk -F\" '/host/ {$2=$6="***"}1' OFS=\" file
<Resource name="MailSession" auth="Container" type="javax.mail.Session"
            mail.smtp.host="***" mail.smtp.user="foo" mail.smtp.passwd="***"
            mail.pop3.host="***" mail.pop3.user="foo" mail.pop3.passwd="***"/>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.