我有一个json文件名test.json,内容如下。
{
"run_list": ["recipe[cookbook-ics-op::setup_server]"],
"props": {
"install_home": "/test/inst1",
"tmp_dir": "/test/inst1/tmp",
"user": "tuser
}
}
我想将此文件读入shell脚本中的变量,然后使用expr提取install_home,user和tmp_dir的值。有人可以帮帮忙吗?
道具= cat test.json
用于将json文件转换为变量。现在我如何使用expr提取值。任何帮助将不胜感激。
对于纯粹的bash解决方案,我建议: github.com/dominictarr/JSON.sh 它可以像这样使用:
./json.sh -l -p < example.json
打印输出如:
["name"] "JSON.sh"
["version"] "0.2.1"
["description"] "JSON parser written in bash"
["homepage"] "http://github.com/dominictarr/JSON.sh"
["repository","type"] "git"
["repository","url"] "https://github.com/dominictarr/JSON.sh.git"
["bin","JSON.sh"] "./JSON.sh"
["author"] "Dominic Tarr <[email protected]> (http://bit.ly/dominictarr)"
["scripts","test"] "./all-tests.sh"
从这里可以轻松实现您的目标
让我们忽略输入文件是JSON文件的事实。如果您只是将其视为输入文本文件,我们只对以下几行感兴趣:
"install_home": "/test/inst1",
"tmp_dir": "/test/inst1/tmp",
"user": "tuser"
一般而言,模式是:
"key"
:
"value"
我们可以使用带有正则表达式的sed
:
"key"
为每个案例硬编码"install_home"
,"tmp_dir"
和"user"
"value"
为(.*)
然后我们可以使用\1
来检索匹配组。 ;t;d
命令的sed
部分将丢弃不匹配的线。
i=$(cat test.json | sed 's/.*"install_home": "\(.*\)".*/\1/;t;d')
t=$(cat test.json | sed 's/.*"tmp_dir": "\(.*\)".*/\1/;t;d')
u=$(cat test.json | sed 's/.*"user": "\(.*\)".*/\1/;t;d')
cat <<EOF
install_home: $i
tmp_dir : $t
user : $u
EOF
哪个输出:
install_home: /test/inst1
tmp_dir : /test/inst1/tmp
user : tuser