2014-09-01 142 views
0

我正在尝试编写一个脚本,该脚本应该从xml文件中获取值。在shell脚本中找不到“错误”

下面是XML文件: -

`<manifestFile> 
    <productInformation> 
     <publicationInfo> 
     <pubID pcsi-selector="P.S.">PACODE</pubID> 
     <pubNumber/> 
    </publicationInfo> 
    </productInformation> 
</manifestFile>` 

和我在我的代码是 : -

#!/bin/sh 

Manifest="" 
Manifest= `/bin/grep 'pcsi-selector="' /LDCManifest.xml | cut -f 2 -d '"'` 
echo $Manifest 

我希望我的结果是附: ,但它一直抛出错误为: -

./abc.sh: P.S.: not found 

我是新来的shell,我无法弄清楚这是什么错误?

+1

PS:不是可能会发现手段shell认为它是一个命令。 – Pieter21 2014-09-01 20:08:59

回答

2

=后面不能有空格。

当您运行此命令:

Manifest= `/bin/grep 'pcsi-selector="' /LDCManifest.xml | cut -f 2 -d '"'` 

这是一样的:

Manifest='' `/bin/grep 'pcsi-selector="' /LDCManifest.xml | cut -f 2 -d '"'` 

这告诉外壳

  1. 运行grep命令。
  2. 采取其输出
  3. 运行该输出作为命令,与环境变量Manifest集到该命令的持续时间的空字符串。

摆脱=之后的空间,你会得到你想要的结果。

但是,您还应该避免使用反引号进行命令替换,因为它们会干扰引用。使用$( ... )代替:

Manifest=$(grep 'pcsi-selector="' /LDCManifest.xml | cut -f2 -d'"') 

此外,使用像grepcut文/基于正则表达式的工具来处理XML是笨重且容易出错。你会好起来的安装类似XMLStarlet

Manifest=$(xmlstarlet sel -t \ 
    -v '/manifestFile/productInformation/publicationInfo/pubID/@pcsiselector' -n \ 
    /LDCManifest.xml) 
+0

删除空间工作,感谢这样的快速响应 – anurag 2014-09-01 20:11:02

+0

其他片段显示错误为: - ./abc.sh:语法错误在第3行:'Manifest = $'意外 我想我错了某处 – anurag 2014-09-01 20:20:49

+0

你用什么shell ,@anurag? '$('...')'在bash中有效,但不是vanilla'/ bin/sh'。 – 2014-09-01 20:24:48

1

或者简单:

grep -oP 'pcsi-selector="\K[^"]+' /LDCManifest.xml 

将打印

P.S. 

分配

Manifest=$(grep -oP 'pcsi-selector="\K[^"]+' /LDCManifest.xml)