test.xml
请,我的文件中有这个 xml 应答器
<ingressAnnotations>nginx.ingress.kubernetes.io/server-snippet: |
location @custom_503 {
return 503 "<html> <head> <meta http-equiv='Content-Type' content='text/html; charset=UTF-8'> <style>...</style></head> <body><img src='https://www.jenkins.io/images/logos/jenkins-is-the-way/j
enkins-is-the-way.png' width='200' height='200' style='display: block; margin-left: auto; margin-right: auto;' alt='jenkins'><center><h2>Jenkins is sleeping, please go to jenkins.betclic.net and click your Maste
r link to wake him up. It will be available in a few minutes. This is the wait !!!</h2></center></body></html>";
}
error_page 503 @custom_503;</ingressAnnotations>
我必须解析我的文件并删除内容。类似这样的操作:
<ingressAnnotations></ingressAnnotations>
请问我该如何通过 sed 做到这一点?我正在尝试这个:
sed -i 's/<ingressAnnotations>*<\/ingressAnnotations>/<ingressAnnotations><\/ingressAnnotations>/g' test.xml
但这不起作用!
答案1
您可以使用 XML 解析器来解析和编辑文件。此命令匹配<ingressAnnonations/>
文档中任意位置的标签并删除其所有内容:
xmlstarlet edit --update '//ingressAnnotations' --value '' test.xml
输出
<?xml version="1.0"?>
<ingressAnnotations/>
一旦您确定转换按预期工作,请包含--inplace
参数(即)以就地编辑文件xmlstarlet edit --inplace --update …
答案2
笨拙,但有效:
$ sed -n '/<ingressAnnotations>/{p; :a; N; /<\/ingressAnnotations>/!ba; s/.*\n//}; p' \
FILENAME | sed -e 's/>.*/>/g' -e 's/.*<\//<\//g'
上式给出:
<ingressAnnotations>
</ingressAnnotations>
已编辑。
要删除模式之间的换行符,请添加| sed -e ':a;N;$!ba;s/\n//g'
管道,因此:
$ sed -n '/<ingressAnnotations>/{p; :a; N; /<\/ingressAnnotations>/!ba; s/.*\n//}; p' \
FILENAME \
| sed -e 's/>.*/>/g' -e 's/.*<\//<\//g' \
| sed -e :a;N;$!ba;s/\n//g'