Parsing data with ifconfig with awk or sed?

I am trying to parse some data from ifconfig output using sed, but I cannot do it correctly. I want the command to retrieve only the number I got after.

For example, I'm interested in retrieving sent bytes:

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'm only interested in "9040627". Is there a way to do this with sed or use awk or other alternatives?

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

+2
source share
3 answers

use grep :

 ifconfig | grep -oP '(?<=RX bytes:)[0-9]*' 

use awk :

 ifconfig | awk -F: '/RX bytes/{print $2+0}' 
+9
source

IMHO there is no standard for ifconfig output. It can (can) vary from system to system and from release to release.

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

 $ cat /sys/class/net/eth0/statistics/rx_bytes 37016050 
+14
source

By default, sed prints each line of input after any changes are made to the line. Since you only want to print something from a line with "RX bytes", you can tell sed not to print every line ( -n ). Therefore, you want to specify the range on which the substitution should be performed, only the line that corresponds to RX bytes , and then perform the substitution and explicitly print the results.

 ifconfig eth1 | sed '/RX bytes/{s|.*RX bytes:\([0-9]*\).*|\1|; p}' 
+1
source

Source: https://habr.com/ru/post/1437874/


All Articles