0

How can I find and store as variables the two numbers followed by "RX bytes:" and "TX bytes:" in this file? I want to calculate with theese values in a simple current bandwidth monitor bash script using an OpenWrt router.

/dev/band1:

br-lan    Link encap:Ethernet  HWaddr 
      inet addr:192.168.1.1  Bcast:192.168.1.255  Mask:255.255.255.0
      UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
      RX packets:3848954 errors:0 dropped:21234 overruns:0 frame:0
      TX packets:4213574 errors:0 dropped:0 overruns:0 carrier:0
      collisions:0 txqueuelen:0
      RX bytes:1206316927 (1.1 GiB)  TX bytes:3385060741 (3.1 GiB)

Thank you for your help!

Kent
  • 189,393
  • 32
  • 233
  • 301
Hiddin
  • 75
  • 4

2 Answers2

3

for example, the RX bytes, you could:

rxBytes=$(yourcmd|grep -Po '(?<=RX bytes:)\d+')

replace the RX with TX you get another variable

EDIT

you could also go with awk:

rxBytes=$(awk -F'RX bytes:' 'NF>1{sub(/ .*$/,"",$2);print $2}')

chg the RX -> TX to get the other one.

Kent
  • 189,393
  • 32
  • 233
  • 301
  • My grep sadly doesn't support pearl style regexp:( Only the extended regexp. – Hiddin May 29 '13 at 13:46
  • Or even `set -- $(ifconfig br-lan | grep -Po '(<=[Rt]X bytes:)\d+')`, which should yield RX in `$1` and TX in `$2`, provided the output format doesn't change – tripleee May 29 '13 at 13:46
  • Could this syntax be converted into extended regular expression format? my grep doesn't support the -P switch. – Hiddin May 29 '13 at 14:39
1
#!/bin/bash
N=(`ifconfig p2p1 | sed -n 's/.*RX bytes:\([0-9]*\) .*TX bytes:\([0-9]*\).*/\1\n\2/p'`)
echo Bytes received ${N[0]}
echo Bytes sent ${N[1]}

This does it with one call to ifconfig, which is probably only important if you want to poll the counters at the same time.

K Boden
  • 626
  • 4
  • 6
  • You can factor out the `grep` into `sed` easily; just add an `-n` option to not print anything by default, and a `p` flag to the substitution to print when it fires. – tripleee May 29 '13 at 13:54
  • Thanks @tripleee, I consolidated the grep hack into sed with -n and p flag. – K Boden May 29 '13 at 15:19