来自多线json的Bash脚本grep变量?

时间:2015-06-20 13:21:24

标签: json bash grep

我有一个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文件。

我是如何实现这一目标的?

1 个答案:

答案 0 :(得分:6)

我不确定您是否要将json文件中的值更改为shell变量的值,或者您是否要将shell变量设置为SensorValue字段的值JSON。

但是,对于这两项任务,您可以使用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等于SensorName的json对象中提取"Intel Core i7-4790: CPU Package"。在jq中您正在使用select()函数:

jq -r '.[] | select(.SensorName == "Intel Core i7-4790: CPU Package").SensorValue' file.json

输出:

32