简体   繁体   English

通过外壳脚本解析XML

[英]Parsing XML via a shell script

i'm using xmlstarlet into a shell script to parse an xml file untitled app.xml with this command, just to get the content of which is a string , and store it on "my_var" : 我正在使用xmlstarlet到shell脚本中,使用此命令来解析未命名为app.xml的xml文件,只是要获取其内容为字符串,并将其存储在“ my_var”上:

my_var=`xmlstarlet sel -t -m "//root/services/service[position=$i]" -v description -n /home/wissem/Bureau/app.xml`

then ,when trying to modify an other xml file untitled strings.xml with the output of the last command , using this command line : 然后,当尝试使用最后一个命令的输出修改另一个未命名为strings.xml的xml文件时,请使用以下命令行:

find /root/AndroidStudioProjects/FacebookMenu/app/src/main/res/values/strings.xml -type f -exec  perl -pi -w -e 's/name=\"text_'$i'\".*\<\/string\>/name=\"text_'$i'\"\>'$my_var'\<\/string\>/g' {} \;

i get the following error : 我收到以下错误:

Substitution replacement not terminated at -e line 1.

i tried to understand the problem by changing severally the string that i'm parsing into my variable , i noticed that the problem appears when i have a "space" on the string ! 我试图通过将解析的字符串分别更改为变量来理解问题,我注意到当字符串上有“空格”时,问题就出现了!

to explain more :for this_is_my_string : it works 解释更多:for this_is_my_string:有效

for this is my string : i get the error. 因为这是我的字符串:我得到了错误。

Yeah, if $my_var contains spaces, the shell will break arguments in $my_var . 是的,如果$my_var包含空格,则外壳程序将破坏$my_var参数。 This should work: 这应该工作:

-e "s;name=\"text_$i\".*</string>;name=\"text_$i\">$my_var</string>;g"

The double quotes prevent your argument from being split. 双引号防止您的论点被分裂。 The double quotes you want to be part of your argument were already quoted with backslashes, which protects them. 您想要成为参数一部分的双引号已经用反斜杠引起来,以保护它们。 And $ variables are expanded when appearing in double quotes. $变量在双引号中出现时扩展。 I've also replaced s/../../g with s;...;...;g so that forward slashed don't need escaping. 我还用s;...;...;g替换了s/../../g ,以便正斜杠不需要转义。 And I'm pretty sure there's no reason to escape the angle brackets. 而且我很确定没有理由逃避尖括号。

I've tested the above with this procedure: 我已经使用以下过程测试了上述内容:

  1. Create /tmp/testq.xml containing: 创建/tmp/testq.xml其中包含:

     <string name="text_100">Blah</string> 
  2. Issue: 问题:

     i=100 my_var="room service" 
  3. Issue: 问题:

     find /tmp/ -name "testq.xml" -exec perl -p -e "s;name=\\"text_$i\\".*</string>;name=\\"text_$i\\">$my_var</string>;g" '{}' \\; 
  4. Result to stdout: 结果到标准输出:

     <string name="text_100">room service</string> 

I don't use -i in the test above because I want to be able to rerun the test any number of times, but -i should not affect the validity of the -e expression. 我不想在上面的测试中使用-i ,因为我希望能够任意次重新运行测试,但是-i不会影响-e表达式的有效性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM