如何用awk拆分单列的输出?
How to split outputs of single column with awk?
我想从 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
我得到本地地址列。
sudo netstat -tulpn | awk '{ print ;}'
现在我只想将端口和 IP 相互拆分并显示在两个单独的列中。最简单的方法是什么? (regex 或类似的东西)
您想在该字段的 last 冒号处拆分。使用 GNU awk:
gawk '{match(, /(.*):(.*)/, m); print m[1], m[2]}'
或
gawk '{print gensub(/(.*):/,"\1 ", 1, )}'
使用非 GNU awk:
mawk '{ip=; sub(/:[^:]+/,"",ip); port=; sub(/.*:/,"",port); print ip,port}'
使用 perl
perl -lapE '$_ = join(" ", $F[3] =~ /(.*):(.*)/)'
将输出通过管道传输到 | column -t
以使其更漂亮。
我想从 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
我得到本地地址列。
sudo netstat -tulpn | awk '{ print ;}'
现在我只想将端口和 IP 相互拆分并显示在两个单独的列中。最简单的方法是什么? (regex 或类似的东西)
您想在该字段的 last 冒号处拆分。使用 GNU awk:
gawk '{match(, /(.*):(.*)/, m); print m[1], m[2]}'
或
gawk '{print gensub(/(.*):/,"\1 ", 1, )}'
使用非 GNU awk:
mawk '{ip=; sub(/:[^:]+/,"",ip); port=; sub(/.*:/,"",port); print ip,port}'
使用 perl
perl -lapE '$_ = join(" ", $F[3] =~ /(.*):(.*)/)'
将输出通过管道传输到 | column -t
以使其更漂亮。