Parsing data from ifconfig with awk or sed?

fazineroso picture fazineroso · Apr 2, 2012 · Viewed 7.4k times · Source

I am trying to parse some data from ifconfig output with sed, but I am not able to do it correctly. I want the command to extract just the number I am after.

For example, I am interested in extracting the bytes sent:

eth1      Link encap:Ethernet  HWaddr 00:00:00:09:15:f7  
      inet addr:192.168.1.2  Bcast:192.168.1.255  Mask:255.255.255.0
      inet6 addr: fe80::92e2:baff:fe08:35c7/64 Scope:Link
      UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
      RX packets:75141 errors:0 dropped:0 overruns:0 frame:0
      TX packets:78046 errors:0 dropped:0 overruns:0 carrier:0
      collisions:0 txqueuelen:1000 
      RX bytes:9040489 (9.0 MB)  TX bytes:34806464 (34.8 MB)

If I use sed:

ifconfig eth1 | sed 's|.*RX bytes:\([0-9]*\).*|\1|g'

I get this output:

eth1      Link encap:Ethernet  HWaddr 00:00:00:09:15:f7  
      inet addr:192.168.1.2  Bcast:192.168.1.255  Mask:255.255.255.0
      inet6 addr: fe80::92e2:baff:fe08:35c7/64 Scope:Link
      UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
      RX packets:75141 errors:0 dropped:0 overruns:0 frame:0
      TX packets:78046 errors:0 dropped:0 overruns:0 carrier:0
      collisions:0 txqueuelen:1000 
9040627

But I am only interested in '9040627' Is there a way to do it with sed, or should I use awk or other alternatives?

Edit: I am using busybox binaries, so my options are limited.

Answer

Andreas Florath picture Andreas Florath · Apr 2, 2012

IMHO there is no standard for the ifconfig - output. It (may) change from system to system and from release to release.

If I were you, I would go for the /sys file system. You get all the information also from there - without the need of post-processing.

$ cat /sys/class/net/eth0/statistics/rx_bytes
37016050