我想计算作为命令输出获得的以字符串“ tun ”开头的条目数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
Run Code Online (Sandbox Code Playgroud)
Adm*_*Bee 12
可以使用grep
和的组合wc
,或者使用awk
第一种方法,使用grep
:
ifconfig | grep "^tun" | wc -l
Run Code Online (Sandbox Code Playgroud)
这将ifconfig
通过管道传递 grep的输出,匹配以字符串开头的所有行tun
(这是使用“锚”指示器完成的^
),然后用于wc
计算grep
输出匹配的行。
正如指出的@schaiba,甚至可以不诉诸wc
凭借grep
的-c
选项,这本身将计算所有匹配的行:
ifconfig | grep -c "^tun"
Run Code Online (Sandbox Code Playgroud)
第二种方法,使用awk
:
ifconfig | awk 'BEGIN {tuns=0}; /^tun/ {tuns++}; END {print tuns}'
Run Code Online (Sandbox Code Playgroud)
这会将输出通过管道传输到awk
. 用awk
单引号括起来的程序' ... '
执行以下操作:
BEGIN { ... }
),初始化一个内部变量tuns
,我们将用于簿记,为 0tun
(由正则表达式表示/^tun/
),增加计数器tuns
END { ... }
),输出结果值tuns
mur*_*uru 12
您可能不需要ifconfig
(或ip
)为此。接口列于/sys/class/net
:
% ls /sys/class/net
eth0 lo tun0 tun1 tun2 wlan0
Run Code Online (Sandbox Code Playgroud)
因此,您可以计算那里的目录,例如:
$ printf "%s\n" /sys/class/net/tun* | wc -l
3
Run Code Online (Sandbox Code Playgroud)