我想从 netstat -tulpn
命令中获取端口和 IP 地址。
输出是这样的:
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 127.0.0.1:3010 0.0.0.0:* LISTEN
tcp 0 0 127.0.0.1:3306 0.0.0.0:* LISTEN
tcp 0 0 127.0.1.1:5334 0.0.0.0:* LISTEN
tcp 0 0 127.0.0.1:6113 0.0.0.0:* LISTEN
tcp6 0 0 ::1:601 :::* LISTEN
udp 0 0 0.0.0.0:5013 0.0.0.0:*
udp 0 0 127.0.1.1:5333 0.0.0.0:*
udp 0 0 0.0.0.0:6341 0.0.0.0:*
udp 0 0 0.0.0.0:53553 0.0.0.0:*
udp 0 0 0.0.0.0:5123 0.0.0.0:*
udp6 0 0 :::4905 :::*
udp6 0 0 :::353 :::*
使用 awk
我得到 Local Address 列。
sudo netstat -tulpn | awk '{ print $4;}'
现在我只想将端口和 IP 相互拆分并显示在两个单独的列中。最简单的方法是什么? (正则表达式 或类似的东西)
最佳答案
您想在该字段的最后 冒号处拆分。使用 GNU awk:
gawk '{match($4, /(.*):(.*)/, m); print m[1], m[2]}'
或
gawk '{print gensub(/(.*):/,"\\1 ", 1, $4)}'
使用非 GNU awk:
mawk '{ip=$4; sub(/:[^:]+/,"",ip); port=$4; sub(/.*:/,"",port); print ip,port}'
用 perl
perl -lapE '$_ = join(" ", $F[3] =~ /(.*):(.*)/)'
将输出通过管道传输到 | column -t
使其美观。
关于regex - 如何用awk拆分单列的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29863017/