parse colon separated value pairs
The script that you linked to is extremely inefficient - you're doing a lot of useless pre-processing...
Use nmcli
in --terse
mode since, per the manual, "this mode is designed and suitable for computer (script) processing", specify the desired fields and pipe the output to jq -sR
e.g.
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]})'
This GNU sed
code isn't jq
, (it isn't a complex conversion), but it seems to work well enough, (even the bars come out OK):
nmcli --mode multiline dev wifi |
sed '/^*/! {s/^[A-Z]*/\L&/
s/ssid/network/
s/: */": "/
s/$/"/
{/^sec/!s/$/,/}
s/^/\t"/}
1 s/^\*.*/[{/
/^\*/ s/.*/},\n{/
$ {p;s/.*/}]/}'
Easier to read standalone pcsvp.sed
script, (save to file, then run chmod +x pcsvp.sed
):
#!/bin/sed -f
# Text lines (the non "*:" lines.)
/^*/! {s/^[A-Z]*/\L&/
s/ssid/network/
s/: */": "/
s/$/"/
{/^sec/!s/$/,/}
s/^/\t"/}
# First JSON line
1 s/^\*.*/[{/
# Middle JSON lines. If a line begins with a '*'...
/^\*/ s/.*/},\n{/
# Last line, close up the JSON.
$ {p;s/.*/}]/}
To run that do:
nmcli --mode multiline dev wifi | ./pcsvp.sed
Note: Since there are doubts about the input file, I've opted to use nmcli
for input instead. At my location this shows about 50 networks, which makes the resulting output too long to quote here.
If the input sample typo is corrected, ./pcsvp.sed input.txt
outputs:
[{
"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": "WEP"
}]