Skip to content

Instantly share code, notes, and snippets.

@kirkins
Last active October 19, 2017 21:50
Show Gist options
  • Save kirkins/d5c9644edf67c76ff73bff86fa760a05 to your computer and use it in GitHub Desktop.
Save kirkins/d5c9644edf67c76ff73bff86fa760a05 to your computer and use it in GitHub Desktop.
First version of nmcli_output to json
#!/usr/bin/env bash
#
# Scan availible wifi networks
# https://unix.stackexchange.com/questions/399222/jq-parse-colon-separated-value-pairs
nmcli_output=$(nmcli dev wifi | sed '$ d' | sed '1d')
#TODO use multi-line version of nmcli to better parse
# function for parsing nmcli output
function get_column {
column=$(printf %s\\n "$nmcli_output" | awk -v column=$1 '
NR==1 {
i=1; p=1;
while(match($0,/^[^ ]+ +/)) {
a[i++] = p;
p += RLENGTH;
$0 = substr($0, RLENGTH+1);
}
}
NR!=1 {
text = substr($0, a[column], a[column+1] ? a[column+1]-a[column] : length);
sub(text, / +$/, "");
print text
}')
column=$(echo $column | sed -e 's/ /,/g')
echo $column
}
# set all variables from nmcli
network=$(get_column 2)
mode=$(get_column 3)
chan=$(get_column 4)
rate=$(get_column 5)
signal=$(get_column 6)
bars=$(get_column 7)
security=$(get_column 8)
# generate json
echo "[" > /tmp/gen_json
network_iter=0
for i in $(echo $network | sed "s/,/ /g")
do
network_iter=$(expr $network_iter + 1)
# Get values for each attribute on each network
network_instance=$(echo $network | cut -d"," -f $network_iter)
mode_instance=$(echo $mode | cut -d"," -f $network_iter)
chan_instance=$(echo $chan | cut -d"," -f $network_iter)
rate_instance=$(echo $rate | cut -d"," -f $network_iter)
signal_instance=$(echo $signal | cut -d"," -f $network_iter)
bars_instance=$(echo $bars | cut -d"," -f $network_iter)
security=$(echo $security | cut -d"," -f $network_iter)
# Parse into json
json="{
\"network\": \"$network_instance\",
\"mode\": \"$mode_instance\",
\"chan\": \"$chan_instance\",
\"rate\": \"$rate_instance\",
\"signal\": \"$signal_instance\",
\"bars\": \"$bars_instance\",
\"security\": \"$security_instance\"
}"
echo "$json", >> /tmp/gen_json
done
# Remove last comma, change later?
perl -0777 -pi -e 's/(.*),(.*?)/\1\2/s' /tmp/gen_json
echo "]" >> /tmp/gen_json
# output json
cat /tmp/gen_json
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment