1

I'm trying to replace the following lines

    <application-bnd>
        <security-role name="appAdmin">
            <user name="appadmin"/>
        </security-role>

        <security-role name="RestAdmin">
            <user name="appadmin"/>
        </security-role>

        <security-role name="ConsoleAdmin">
            <user name="appadmin"/>
        </security-role>

        <security-role name="ConsoleUser">
            <special-subject type="ALL_AUTHENTICATED_USERS" />
        </security-role>
    </application-bnd> 

to

    <application-bnd>
        <security-role name="ALL_AUTHENTICATED_CONTAINER">
        <special-subject type="ALL_AUTHENTICATED_USERS"/>
        </security-role>
    </application-bnd> 

with sed command.

  1. application-bnd element is part section of big xml, I just want to find the multiple lines with above features, then replace it.
  2. The number of security-role elements is not fixed. Any suggestions?
che yang
  • 395
  • 3
  • 18
  • 1
    Why don't you try some xml parsers? – Avinash Raj Nov 03 '14 at 09:30
  • which are the keys attributs (is there only 1 `application-bnd`, all the security tole mentionned MUST be in, special-subject is uniq, ...) ? – NeronLeVelu Nov 03 '14 at 12:09
  • I think @AvinashRaj is alluding to this answer on using RegEx to parse HTML, and the same reasoning applies to parsing XML with RegEx: http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 – outis nihil Nov 03 '14 at 22:07

2 Answers2

1

Here you have a solution with awk instead of sed that would do your job

awk '
BEGIN { 
  enable=0; 
  lineToRemove == 0;
}
/<application-bnd/ { 
  replacementStart=1; 
}
/<\/application-bnd/ {
  replacementStart=0; enable=0;
}
/<security-role/ {
  if (replacementStart==1) enable=1;
}
/<\/security-role/ {
  if (replacementStart==1) enable=0; lineToRemove = 1; }
/ALL_AUTHENTICATED_USERS/ {
  print "<security-role name=\"ALL_AUTHENTICATED_CONTAINER\">";
  print "<special-subject type=\"ALL_AUTHENTICATED_USERS\"/>";
  print "</security-role>";
}
/.*/ { 
  if (enable==0 && lineToRemove == 0) print $0;
  lineToRemove = 0;
}' text.xml
Christophe
  • 2,131
  • 2
  • 21
  • 35
0

you can try this solution but I remove new lines from your file so this won't work if you don't want newlines to be removed or if you have security-roles after the application-bnd

cat text.xml | tr -d '\n' | sed 's%<security-role.*<security-role%<security-role name="ALL_AUTHENTICATED_CONTAINER"><security-role%'
Christophe
  • 2,131
  • 2
  • 21
  • 35
  • Thank you. But application-bnd is part section of big xml, I just want to find the multiple lines with above features, then replace it. can you help? – che yang Nov 03 '14 at 09:39
  • It's impossible for me to make them in one line as I mentioned that it's only a element of a large xml. – che yang Nov 03 '14 at 09:48