簡體   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