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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 15:02:12  来源:igfitidea点击:

Use grep to parse a key from a json file and get the value

jsonbashawksed

提问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

\Kis 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 jqfor the task :

使用专门的工具jq来完成任务:

Had your filelooked like

如果你file看起来像

[
{
"test": 12,
"job": 45,
"task": 11
}
]

below stuff would get you home

下面的东西会让你回家

jq ".[].job" file

Had your filelooked 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 secondcolumn of that line. awk option -Fis used to set the column separator as :followed by any number of spacesor tabs.

上面的命令匹配任何"job"位于行首的行,然后打印该second行的列。awk 选项-F用于将列分隔符设置为:后跟任意数量的spacestabs

If you want to store this value in bash variable job_val:

如果要将此值存储在 bash 变量中job_val

job_val=$(awk -F ':[ \t]*' '/^.*"job"/ {print }' filename)