awkgrepbusyboxash

parsing output with awk


I am trying to construct a small shell script that takes the output from this command: nc 127.0.0.1 5556 2>/dev/null (output shown below) and parse it into individual variables so I can transmit via mqtt client. I think I need to use grep or perhaps awk.

So for example, If I want to parse the 5 values associated with wind0 into 5 individual variables how would I do that. I need to end up with $a=220, $b=0.0, $c=0.0, $d=8.2, and $e=0.

Thank you!

Baobab

Edit: turns out that the system I am trying this on is OpenWRT based so apparently uses ash or BusyBox and not bash.

20201103061623 th0 8.2 39 -4.9 0
20201103061629 wind0 220 0.0 0.0 8.2 0
20201103061611 rain0 0.0 153.8 0.0 0
20201103061547 thb0 22.3 32 4.8 901.7 1004.5 0 1
20201103061628 data10 0.00 0
20201103061628 data11 1.29 0
20201103061628 data12 0.00 0
20201103061628 data13 11.00 0
20201103061628 data15 108.00 0
20201103061628 data16 3.00 0
20201103061628 t9 50.5 0

Solution

  • You can do something like this:

    while read -r a b c d e; do
         echo "a=$a, b=$b, c=$c, d=$d, e=$e"
    done < <(nc ... 2>&1 | awk -F '[[:blank:]]+wind0[[:blank:]]+' 'NF>1{print $2}')
    
    a=220, b=0.0, c=0.0, d=8.2, e=0
    

    Replace nc ... with your actual nc command line.


    If you're not using bash then use:

    nc ... 2>&1 | awk -F '[[:blank:]]+wind0[[:blank:]]+' 'NF>1{print $2}' |
    while read -r a b c d e; do
         echo "a=$a, b=$b, c=$c, d=$d, e=$e"
    done