我想计算以字符串“开头的条目数屯“我得到的命令输出ifconfig
。
例如,如果这是我的输出,我想数为2。我尝试使用grep
,但仍然没有解决。
docker0: flags=4099<UP,BROADCAST,MULTICAST> mtu 1500
inet 172.0.0.1 netmask 255.255.0.0 broadcast 172.17.255.255
ether 02:42:16:73:86:ba txqueuelen 0 (Ethernet)
RX packets 0 bytes 0 (0.0 B)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 0 bytes 0 (0.0 B)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
enp0s31f6: flags=4099<UP,BROADCAST,MULTICAST> mtu 1500
ether 00:00:00:00:00:00 txqueuelen 1000 (Ethernet)
RX packets 0 bytes 0 (0.0 B)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 0 bytes 0 (0.0 B)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
device interrupt 16 memory 0xa1300000-a1320000
lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536
inet 127.0.0.1 netmask 255.0.0.0
inet6 :: prefixlen 128 scopeid 0x10<host>
loop txqueuelen 1000 (Local Loopback)
RX packets 905 bytes 80293 (80.2 KB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 905 bytes 80293 (80.2 KB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
tun0: flags=4305<UP,POINTOPOINT,RUNNING,NOARP,MULTICAST> mtu 1500
inet 00.00.00.00 netmask 255.255.255.255 destination 192.168.105.77
inet6 :: prefixlen 64 scopeid 0x20<link>
unspec 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00 txqueuelen 100 (UNSPEC)
RX packets 438 bytes 52174 (52.1 KB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 457 bytes 33911 (33.9 KB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
tun1: flags=4305<UP,POINTOPOINT,RUNNING,NOARP,MULTICAST> mtu 1500
inet 0.0.0.0 netmask 255.255.255.255 destination 192.168.104.61
inet6 :: prefixlen 64 scopeid 0x20<link>
unspec 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00 txqueuelen 100 (UNSPEC)
RX packets 0 bytes 0 (0.0 B)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 10 bytes 584 (584.0 B)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
答案1
可以使用grep
和的组合wc
,或者使用awk
第一种方法, 使用grep
:
ifconfig | grep "^tun" | wc -l
这将通过 grep 管道输出ifconfig
,匹配以字符串开头的所有行tun
(这是使用“锚”指示符完成的^
),然后用于对输出匹配的wc
行进行计数。grep
正如所指出的通过@schaiba,甚至可以不借助wc
的grep
选项-c
,该选项将自行计算所有匹配的行:
ifconfig | grep -c "^tun"
第二种方法, 使用awk
:
ifconfig | awk 'BEGIN {tuns=0}; /^tun/ {tuns++}; END {print tuns}'
这会将输出通过管道传输到awk
.该awk
程序用单引号括起来' ... '
,执行以下操作:
- 在开头 (
BEGIN { ... }
) 处,初始化一个内部变量tuns
,我们将用它来记账,为 0 - 在主循环中,对于遇到的以字符串开头的每一行
tun
(由正则表达式 表示/^tun/
),增加计数器tuns
- 输入完成后,(
END { ... }
)输出结果值tuns
答案2
您可能不需要ifconfig
(或ip
) 为此。接口列于/sys/class/net
:
% ls /sys/class/net
eth0 lo tun0 tun1 tun2 wlan0
因此,您可以计算那里的目录,例如:
$ printf "%s\n" /sys/class/net/tun* | wc -l
3