Text-Processing

解析冒號分隔值對

  • July 11, 2021

我編寫了一個轉換為 json 的腳本nmcli --mode multiline dev wifi,但我發現它不一致*(當結果有空格時中斷)*、長且難以閱讀。

我想知道是否可以將結果直接輸入到jq. 輸出如下所示:

*:                                       
SSID:                                   VIDEOTRON2255
MODE:                                   Infra
CHAN:                                   11
RATE:                                   54 Mbit/s
SIGNAL:                                 69
BARS:                                   ▂▄▆_
SECURITY:                               WPA1 WPA2
*:                                      * 
SSID:                                   VIDEOTRON2947
MODE:                                   Infra
CHAN:                                   6
RATE:                                   54 Mbit/s
SIGNAL:                                 49
BARS:                                   ▂▄__
SECURITY:                               WPA1 WPA2

我正在尋找生成這樣的東西:

[{
   "network": "VIDEOTRON2255",
   "mode": "Infra",
   "chan": "11",
   "rate": "54 Mbit/s",
   "signal": "69",
   "bars": "▂▄▆_",
   "security": "WPA1 WPA2"
},
{
   "network": "VIDEOTRON2947",
   "mode": "Infra",
   "chan": "6",
   "rate": "54 Mbit/s",
   "signal": "49",
   "bars": "▂▄__",
   "security": "WPA1 WPA2"
}]

是的,我之前確實問過一個相關的問題。這是我根據Gilles answer編寫的第一個腳本,它適用於某些值但不適用或有空格。security``rate

您連結到的腳本效率極低-您正在做很多無用的預處理…在模式下

使用,因為根據手冊,“此模式設計用於電腦(腳本)處理”,請指定所需的欄位並將輸出通過管道傳輸到例如nmcli``--terse``jq -sR

printf '%s' "$(nmcli -f ssid,mode,chan,rate,signal,bars,security -t dev wifi)" | \
jq -sR 'split("\n") | map(split(":")) | map({"network": .[0],
                                            "mode": .[1],
                                            "channel": .[2],
                                            "rate": .[3],
                                            "signal": .[4],
                                            "bars": .[5],
                                            "security": .[6]})'

引用自:https://unix.stackexchange.com/questions/399222