繁体   English   中英

Bash从多行JSON脚本Grep变量?

[英]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

  • 遍历bash中的json值
jq -r '.[].SensorValue' file.json | while read -r value ; do
    # Do something useful with the value
    echo "$value"
done
  • 从bash修改json文件
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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM