如何在bash脚本中提取已提取的XML文本的特定文本

时间:2011-02-20 05:47:21

标签: xml bash unix sed

我设法从XML文件中提取值:

<--more labels up this line>
<ExtraDataItem name="GUI/LastVMSelected" value="14cd3204-4774-46b8-be89-cc834efcba89"/>
<--more labels and text down this line-->

使用这个:

  UUID=$(sed -ne '/name="GUI\/LastVMSelected"/s/.*value="\([^"]*\)".*/\1/p' inputfile.xml)
       echo $UUID

我在控制台中有这个结果:

14cd3204-4774-46b8-be89-cc834efcba89

就是这样!但是现在,我需要使用该UUID来访问同一XML文件的另一部分,我以前没有显示过。我简化了XML文件只是为了显示最相关的标签:

      <--more labels up this line>
 <ExtraDataItem name="GUI/LastVMSelected" value="14cd3204-4774-46b8-be89-cc834efcba89"/>
      <--more labels and text down this line-->
      <MachineEntry uuid="{14cd3204-4774-46b8-be89-cc834efcba89}" src="Machines/SomeMachine/SomeMachine.xml"/>
 <--more labels and text down this line-->

我需要获得“SomeMachine”,不带扩展名,只需要该名称。我尝试自己添加一些内容:

UUID=$(sed -ne '/name="GUI\/LastVMSelected"/s/.*value="\([^"]*\)".*/\1/p' inputfile.xml)    
LastVMname=$(sed -ne '/MachineEntry uuid="{'$UUID'}"/s/.*src="Machines\([^"]*\).xml".*/\1/p' inputfile.xml)
    echo $LastVMname

但我得到了这个输出:

/SomeMachine/SomeMachine

我不知道如何摆脱/ SomeMachine / SomeMachine,只需要“SomeMachine”。 Sed文档很混乱:S

1 个答案:

答案 0 :(得分:2)

您可以为替换命令使用替代分隔符,并在数据中的斜杠上键入。

LastVMname=$(sed -ne '/MachineEntry uuid="{'$UUID'}"/s|.*src="Machines.*/\(.*\).xml".*|\1|p' inputfile.xml)

然而,this way madness lies

您应该使用xmlstarlet之类的XML解析器。类似的东西:

uuid=$(xmlstarlet sel -t -m "//ExtraDataItem[@name='GUI/LastVMSelected']" -v @value)
LastVMname=$(xmlstarlet sel -t -m "//MachineEntry[uuid='$uuid'] -v @src)
LastVMname=${LastVMname##*/}    # strip up to and including the last slash
LastVMname=${LastVMname%.*}     # strip the extension