2

I am trying to create a JSON compatible output in bash that can be read by nodejs & python:

{"link":XX,"signal":YY,"noise":ZZ}

here's the unfiltered result:

iwconfig wlan0            
wlan0     IEEE 802.11bg  ESSID:"wifi@someplace"  Nickname:"<WIFI@REALTEK>"
          Mode:Managed  Frequency:2.452 GHz  Access Point: C8:4C:75:20:B4:8E   
          Bit Rate:54 Mb/s   Sensitivity:0/0  
          Retry:off   RTS thr:off   Fragment thr:off
          Encryption key:A022-1191-3A   Security mode:open
          Power Management:off
          Link Quality=100/100  Signal level=67/100  Noise level=0/100
          Rx invalid nwid:0  Rx invalid crypt:0  Rx invalid frag:0
          Tx excessive retries:0  Invalid misc:0   Missed beacon:0

But after applying my filters:

iwconfig wlan0 | grep Link | tr -d '/100' | tr '=' ' ' | xargs | awk '{printf "{\"link\":"$3",\"signal\":"$6",\"noise\":"$9"}"}'

I am getting erratic and incomplete results:

{"link":98,"signal":6,"noise":}
{"link":Signal,"signal":Noise,"noise":}

The "noise" value is never captured, and sometimes printf returns the wrong chunk.

Is there a more 'reliable' way of doing this ?

1
  • Thanks for all of the suggestions, but I really needed to fix my version of the code as I really struggle with REGEX and selected @Thrustmaster solution in the end. Commented Dec 17, 2013 at 0:34

3 Answers 3

1

The problem with the code in your question is here:

tr -d '/100'

What that command does it simply delete all the characters: '/', '1', '0'.

From the manual for tr,

  -d, --delete
      delete characters in SET1, do not translate

Thats not something you'd want. What you want is to replace the entire string /100 with "".

Use: sed 's/\/100//g' instead.

... | grep Link | sed 's/\/100//g' | tr '=' ' ' | awk '{printf "{\"link\":"$3",\"signal\":"$6",\"noise\":"$9"}"}'
Sign up to request clarification or add additional context in comments.

Comments

0

You could restructure the output using perl, by piping the output through the following command:

perl -n -E 'if ($_ =~ qr{Link Quality=(\d+)/100.*?Signal level=(\d+)/100.*?Noise level=(\d+)/100}) { print qq({"link":$1,"signal":$2,"noise":$3}); }'

Comments

0

Using awk it is quite simple:

awk -F '[ =/]+' '$2=="Link"{printf "{\"%s\":%s,\"%s\":%s,\"%s\":%s}\n", 
                                   $2, $5, $6, $8, $10, $12}'
{"Link":100,"Signal":67,"Noise":0}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.