2014-11-03 72 views
1

多行我试图用sed命令来替换以下行SED替代XML

<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> 

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

  1. application-bnd元素是big xml的一部分,我只想找到具有上述特性的多行,然后替换它。
  2. 安全角色元素的数量不固定。有什么建议么?
+1

你为什么不尝试一些XML解析器的解决方案? – 2014-11-03 09:30:39

+0

哪些是关键属性(是否只有1个'application-bnd',所有的安全容差都必须在,特殊主题是uniq,...)? – NeronLeVelu 2014-11-03 12:09:10

+0

我认为@AvinashRaj暗指使用RegEx解析HTML的这个答案,同样的推理适用于用RegEx解析XML:http://stackoverflow.com/questions/1732348/regex-match-open-tags-except- xhtml-self-contained-tags/1732454#1732454 – 2014-11-03 22:07:43

回答

0

在这里,你有awk的,而不是sed的,会做你的工作

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 
+0

太棒了!有用。 – 2014-11-03 13:49:58

+0

虽然你想失去“猫”。 – tripleee 2014-11-04 14:57:20

+0

我编辑并从我的答案中删除了猫,这是一个坏习惯,我有thx的评论 – 2014-11-05 07:06:14

0

你可以试试这个解决办法,但我删除你的文件的新行,以便这不会工作,如果你不想被删除换行符做,或者如果您有安全角色的应用程序,BND

cat text.xml | tr -d '\n' | sed 's%<security-role.*<security-role%<security-role name="ALL_AUTHENTICATED_CONTAINER"><security-role%' 
+0

谢谢。但是application-bnd是big xml的一部分,我只想找到具有上述特征的多行,然后替换它。你能帮我吗? – 2014-11-03 09:39:55

+0

正如我刚才提到的,它只是一个大XML的元素,所以我不可能将它们制作成一行。 – 2014-11-03 09:48:43