【问题标题】:save output of command in array将命令的输出保存在数组中
【发布时间】:2017-11-30 14:19:53
【问题描述】:

我正在使用 FreeBSD 服务器,哪里没有 bash,如何将命令保存在数组中? 我有命令,可以工作grep '<description' amitOrServer.xml | cut -f2 -d">" | cut -f1 -d"<"

我试图从 xml 文件中将变量保存在 <description /> 中。 XML 文件如下所示:

<amitOrServer>
 <item> 
  <title>AMIT</title>
  <description>DISABLE</description> 
 </item> 
 <item> 
  <title>GPS</title> 
  <description>DISABLE</description>  
 </item>  
</amitOrServer>

我需要将 DISABLE 参数保存在变量中,以便稍后在 shell 脚本中使用它们。

我在变量中保存参数的脚本。

 #!/bin/sh

    chosenOne=( $(grep '<description' amitOrServer.xml | cut -f2 -d">" | cut -f1 -d"<") )
    amit= "$chosenOne[$1]" #"ENABLE"
    gps= "$chosenOne[$2]" #"DISABLE"

我遇到了语法错误:单词意外(期望“)”) 谁能帮帮我,如何将这些参数从 XML 文件中保存到数组中?

【问题讨论】:

标签: xml shell freebsd


【解决方案1】:

试试这个:

#!/bin/sh

AMIT=$(grep AMIT -A1 items.xml | awk -F '[<>]' '/description/{print $3}')
GPS=$(grep GPS -A1 items.xml | awk -F '[<>]' '/description/{print $3}')

echo ${AMIT}
echo ${GPS}

如果你有 python,这也可以工作:

from xml.dom import minidom

xmldoc = minidom.parse('items.xml')
itemlist = xmldoc.getElementsByTagName('item')

out = {}
for i in itemlist:
    title = i.getElementsByTagName('title')[0].firstChild.nodeValue
    description = i.getElementsByTagName('description')[0].firstChild.nodeValue
    out[title] = description

print out
print out["AMIT"]
print out["GPS"]

【讨论】:

    猜你喜欢
    • 2017-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-03
    • 2011-12-31
    • 1970-01-01
    • 2016-07-13
    相关资源
    最近更新 更多