bash 使用 grep 从 json 文件中解析一个键并获取值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38878724/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Use grep to parse a key from a json file and get the value
提问by Ajov Crowe
Can someone suggest how I can get the value 45 after parsing an example json text as shown below :
有人可以建议我在解析示例 json 文本后如何获得值 45,如下所示:
....
"test": 12
"job": 45
"task": 11
.....
Please note that I am aware of tools like jq and others but this requires it to be installed.
请注意,我知道 jq 等工具,但这需要安装它。
I am hoping to get this executed using grep, awk or sed command.
我希望使用 grep、awk 或 sed 命令执行此操作。
回答by anubhava
You can use grep -oP
(PCRE):
您可以使用grep -oP
(PCRE):
grep -oP '"job"\s*:\s*\K\d+' file
45
\K
is used for reseting the previously matched data.
\K
用于重置之前匹配的数据。
回答by Ed Morton
awk -F'[[:space:]]*:[[:space:]]*' '/^[[:space:]]*"job"/{ print }'
sed -n 's/^[[:space:]]*"job"[[:space:]]*:[[:space:]]*//p'
回答by sjsam
Use specialized tools like jq
for the task :
使用专门的工具jq
来完成任务:
Had your file
looked like
如果你file
看起来像
[
{
"test": 12,
"job": 45,
"task": 11
}
]
below stuff would get you home
下面的东西会让你回家
jq ".[].job" file
Had your file
looked like
如果你file
看起来像
{
"stuff" :{
.
.
"test": 12,
"job": 45,
"task": 11
.
.
}
}
below
以下
jq ".stuff.job" file
would get you home.
会让你回家。
回答by sps
Using awk
, if you just want to print it:
使用awk
, 如果您只想打印它:
awk -F ':[ \t]*' '/^.*"job"/ {print }' filename
Above command matches any line that has "job"
at the beginning of a line, and then prints the second
column of that line. awk option -F
is used to set the column separator as :
followed by any number of spaces
or tabs
.
上面的命令匹配任何"job"
位于行首的行,然后打印该second
行的列。awk 选项-F
用于将列分隔符设置为:
后跟任意数量的spaces
或tabs
。
If you want to store this value in bash variable job_val
:
如果要将此值存储在 bash 变量中job_val
:
job_val=$(awk -F ':[ \t]*' '/^.*"job"/ {print }' filename)