使用 sed/awk 格式化 ifconfig

使用 sed/awk 格式化 ifconfig

ifconfig我在 OpenSUSE 上使用。当我跑步时ifconfig eth0我得到

eth0  Link encap:Ethernet  HWaddr CE:FD:75:DF:A5:6D
      inet addr:172.16.4.177  Bcast:172.16.5.255  Mask:255.255.254.0
      inet6 addr: fe80::adfd:75ef:fedf:v56d/64 Scope:Link
      UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
      RX packets:11812456 errors:0 dropped:2 overruns:0 frame:0
      TX packets:7000495 errors:0 dropped:0 overruns:0 carrier:0
      collisions:0 txqueuelen:1000
      RX bytes:2591436376 (2471.3 Mb)  TX bytes:9196901478 (8770.8 Mb)

sed我希望对其进行格式化,以便使用以下命令在新行上返回每个参数awk

   eth0  
         Link encap:Ethernet
         HWaddr CE:FD:75:DF:A5:6D
         inet addr:172.16.4.177  
         Bcast:172.16.5.255  
         Mask:255.255.254.0
         inet6 addr: fe80::adfd:75ef:fedf:v56d/64 
         Scope:Link
         UP BROADCAST RUNNING MULTICAST  MTU:1500  
         Metric:1
         RX packets:11812456 
         errors:0 
         dropped:2
         overruns:0 
         frame:0
         TX packets:7000495 
         errors:0
         dropped:0 
         overruns:0 
         carrier:0
         collisions:0
         txqueuelen:1000
         RX bytes:2591436376 (2471.3 Mb)
         TX bytes:9196901478 (8770.8 Mb)

我已经尝试过了ifconfig eth0 | sed 's/ /\r/',但这似乎并没有在双倍空间上分开。

答案1

你可以从

sed 's/\(:[^: ]\+\) \([^(]\)/\1\n\2/g;s/\()\)/\1\n/;s/^ \+//'

它应该足够接近,并且很可能可以进一步简化和优化。结果:

eth0  Link encap:Ethernet
 HWaddr CE:FD:75:DF:A5:6D
inet addr:172.16.4.177
 Bcast:172.16.5.255
 Mask:255.255.254.0
inet6 addr: fe80::adfd:75ef:fedf:v56d/64
Scope:Link
UP BROADCAST RUNNING MULTICAST  MTU:1500
 Metric:1
RX packets:11812456
errors:0
dropped:2
overruns:0
frame:0
TX packets:7000495
errors:0
dropped:0
overruns:0
carrier:0
collisions:0
txqueuelen:1000
RX bytes:2591436376 (2471.3 Mb)
  TX bytes:9196901478 (8770.8 Mb)

答案2

以下脚本使用了=符号的中间替换(您可以随意更改为您想要的任何符号):

#!/bin/sed -f
s/\s\+\s/=/g
/:[^=:]\+:/s/:[^=:]\+ /&=/g
s/^=/\t/
s/ *=$//
s/ *=/\n\t/g

所以

ifconfig eth0 | sed -f script.above

输出:

eth0
    Link encap:Ethernet
    HWaddr 74:2f:68:8b:b8:6e
    inet addr:192.168.1.247
    Bcast:192.168.1.255
    Mask:255.255.255.224
    inet6 addr: fe80::762f:68ff:fe8b:b86e/64
    Scope:Link
    UP BROADCAST RUNNING MULTICAST
    MTU:1500
    Metric:1
    RX packets:3128543
    errors:0
    dropped:1
    overruns:0
    frame:0
    TX packets:1346967
    errors:0
    dropped:0
    overruns:0
    carrier:0
    collisions:0
    txqueuelen:1000
    RX bytes:4538616348 (4.5 GB)
    TX bytes:118149772 (118.1 MB)

相关内容