Search code examples
linuxawkiperf

Parsing a non-regular command output


I have the following output of iperf version 2 running on LEDE OS. I am trying to parse the output to get the number before the Mbits/sec which is the average throughput of the IPERF session. However, it seems the separation between each column does not match certain number of spaces nor tabs. In addition, the CSV format generated by iperf generates strange results, as a result I have to rely on the regular output of iperf. Any suggestion how to parse the output using either regular expression or awk command?

The iperf command:

iperf -c 10.0.0.7 -t 10 -i 0.1 -f m

The output:

[  3] 0.00-10.00 sec  1889 MBytes  1584 Mbits/sec  15114/0          0     
2483K/3302 us

Solution

  • You can use grep for those.

    iperf -c 10.0.0.7 -t 10 -i 0.1 -f m | grep -o -E '\w+ Mbits/sec'
    

    OR to be more accurate:

    iperf -c 10.0.0.7 -t 10 -i 0.1 -f m | grep -o -E '[0-9]+ Mbits/sec'
    

    To get only the digits, you can use yet another regex,

    iperf -c 10.0.0.7 -t 10 -i 0.1 -f m | grep -Po '[[:digit:]]+ *(?=Mbits/sec)'
    

    Above, [[:digit:]]+ and [0-9]+ are same and matches the digits in the line.

    For FreeBSD grep in MacOS X, -P will not work. Instead use perl directly,

    iperf -c 10.0.0.7 -t 10 -i 0.1 -f m | perl -nle 'print $& if m{\d+ *(?=Mbits/sec)}'