简体   繁体   English

Bash从多行JSON脚本Grep变量?

[英]Bash scripting grep variable from multilined json?

I have a JSON file that has many instances like this..: 我有一个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
},

And so forth. 依此类推。 I need to assign a variable, say var1 to the sensor value in: 我需要在以下位置为传感器值分配一个变量,例如var1:

{
  "SensorApp": "Open Hardware Monitor",
  "SensorClass": "Temperature",
  "SensorName": "Intel Core i7-4790: CPU Package",
  "SensorValue": "32",
  "SensorUnit": "C",
  "SensorUpdateTime": 0
},

I've tried a few questions already in stackoverflow, however none of them seem to work with multi-lined JSON files. 我已经在stackoverflow中尝试了一些问题,但是似乎没有一个问题适用于多行JSON文件。

Any ideas how i can achieve this? 任何想法,我怎么能做到这一点?

I'm not sure if you want to change the value in the json file to a value of a shell variable or if you want to set a shell variable to the value of the SensorValue field in the json. 我不确定是否要将json文件中的值更改为shell变量的值,或者是否要将shell变量设置为json中的SensorValue字段的值。

However, for both tasks you can use jq : 但是,对于这两个任务,您都可以使用jq

  • Iterating over json values in bash 遍历bash中的json值
jq -r '.[].SensorValue' file.json | while read -r value ; do
    # Do something useful with the value
    echo "$value"
done
  • Modifying a json file from bash 从bash修改json文件
VALUE=123
jq ".[].SensorValue = $VALUE" file.json

Update : In comments you told you want to extract the SensorValue out of that json object where SensorName equals "Intel Core i7-4790: CPU Package" . 更新 :在评论你告诉你要提取的SensorValue指出,JSON对象,其中的SensorName等于"Intel Core i7-4790: CPU Package" In jq you are using the select() function for that: jq您正在使用select()函数:

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

Output: 输出:

32

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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