请注意,ifconfig输出因平台而异,因此这不是一种非常便携的方法.
至于sed解决方案,我认为你需要将解析分解为多个步骤,这样的事情应该可行(GNU sed):
parse.sed
s/^([^ ]+) */\1\n/ # interface name
s/Link encap:(.*)( |$).*/\1/ # link encapsulation
N # append next line to PS
/inet addr/! s/\n[^\n]*$/\n0.0.0.0\n/ # use 0.0.0.0 if no "inet addr"
s/ *inet addr:([^ ]+).*/\1\n/ # capture ip address if present
s/\n[^\n]*$// # cleanup the last line
s/([^\n]+)\n([^\n]+)\n([^\n]+)/IFACE \1 \3 \2/p # print entry
s/.*// # empty PS
: loop # \
N # \
/^\n$/b # skip until next empty line
s/.*// # /
b loop # /
说明
我们的想法是使用换行符分隔符捕获模式空间中的所有相关信息.
测试
像这样运行:
ifconfig -a | sed -rf parse.sed
IFACE eth0 192.168.30.8 Ethernet
IFACE eth1 212.233.112.171 Ethernet
IFACE lo 127.0.0.1 Local Loopback
IFACE pan0 0.0.0.0 Ethernet
IFACE tunl0 IPIP Tunnel