[英]Bash scripting grep variable from multilined json?
我有一个JSON文件,其中包含许多这样的实例:
{
"SensorApp": "Open Hardware Monitor",
"SensorClass": "Temperature",
"SensorName": "Intel Core i7-4790: CPU Core #4",
"SensorValue": "31",
"SensorUnit": "C",
"SensorUpdateTime": 0
},
{
"SensorApp": "Open Hardware Monitor",
"SensorClass": "Temperature",
"SensorName": "Intel Core i7-4790: CPU Package",
"SensorValue": "32",
"SensorUnit": "C",
"SensorUpdateTime": 0
},
{
"SensorApp": "Open Hardware Monitor",
"SensorClass": "Clock",
"SensorName": "Intel Core i7-4790: CPU Core #1",
"SensorValue": "3899.165",
"SensorUnit": "MHz",
"SensorUpdateTime": 0
},
依此类推。 我需要在以下位置为传感器值分配一个变量,例如var1:
{
"SensorApp": "Open Hardware Monitor",
"SensorClass": "Temperature",
"SensorName": "Intel Core i7-4790: CPU Package",
"SensorValue": "32",
"SensorUnit": "C",
"SensorUpdateTime": 0
},
我已经在stackoverflow中尝试了一些问题,但是似乎没有一个问题适用于多行JSON文件。
任何想法,我怎么能做到这一点?
我不确定是否要将json文件中的值更改为shell变量的值,或者是否要将shell变量设置为json中的SensorValue
字段的值。
但是,对于这两个任务,您都可以使用jq
:
jq -r '.[].SensorValue' file.json | while read -r value ; do
# Do something useful with the value
echo "$value"
done
VALUE=123
jq ".[].SensorValue = $VALUE" file.json
更新 :在评论你告诉你要提取的SensorValue
指出,JSON对象,其中的SensorName
等于"Intel Core i7-4790: CPU Package"
。 在jq
您正在使用select()
函数:
jq -r '.[] | select(.SensorName == "Intel Core i7-4790: CPU Package").SensorValue' file.json
输出:
32
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.