在几台不同的linux机器中,我必须计算不同端口的tcp套接字连接的数量及其状态。最后打印出来的可能是这样的。
49570 10.10.10.10:13062 ESTABLISHED
783 10.10.10.10:18080 CLOSE_WAIT
493 10.10.10.10:18082 CLOSE_WAIT
109 10.10.10.10:18080 SYN_RECV
17 10.10.10.10:15062 TIME_WAIT
15 10.10.10.10:15062 ESTABLISHED第一列是计数,第二列是ip:端口,第三列是状态。
我想要做的是重新格式化输出,这样它就像这样出来了
13062 15062 18080 18082
ESTABLISHED 49570 15 0 0
CLOSE_WAIT 0 0 783 493
SYN_RECV 0 0 109 0
TIME_WAIT 0 17 0 0 ip,是不同的机器,有可能有更多的端口,或更多的状态,或更少。有可能用awk来实现这一点吗。有没有人有关于如何得到这个的例子。
很抱歉,我很难粘贴所需的输入/输出结果,就像现在一样。提前谢了。
发布于 2016-04-17 15:41:44
$ cat tst.awk
{
sub(/.*:/,"",$2)
ports[$2]
statuses[$3]
counts[$2,$3] = $1
for (i=1;i<=NF;i++) {
maxWidth[i] = (length($i) > maxWidth[i] ? length($i) : maxWidth[i])
}
}
END {
statusWidth = maxWidth[3]
otherWidth = (maxWidth[1] > maxWidth[2] ? maxWidth[1] : maxWidth[2]) + 2
printf "%-*s", statusWidth, ""
for (port in ports) {
printf "%*s", otherWidth, port
}
print ""
for (status in statuses) {
printf "%-*s", statusWidth, status
for (port in ports) {
printf "%*d", otherWidth, counts[port,status]
}
print ""
}
}
$ awk -f tst.awk file
13062 15062 18080 18082
SYN_RECV 0 0 109 0
CLOSE_WAIT 0 0 783 493
ESTABLISHED 49570 15 0 0
TIME_WAIT 0 17 0 0发布于 2016-04-17 15:49:54
下面是另一个gawk解决方案。
awk -F"[: ]+" 'BEGIN{delim="\t"}
{ports[$3]; status[$3][$4]=$1; st[$4]}
END{str=delim
for(key in ports){str=str""delim""key}
print str
for(k in st){
str =k
for (key in ports) {
str = str""delim""(status[key][k] ? status[key][k] : 0)
}
print str
}
}' test.txt输出(如果希望空白而不是"\t“作为分隔符,请将delim="\t"更改为delim=" "):
15062 13062 18080 18082
SYN_RECV 0 0 109 0
CLOSE_WAIT 0 0 783 493
ESTABLISHED 15 49570 0 0
TIME_WAIT 17 0 0 0对于此输入(即,在没有前导空格的情况下):
49570 10.10.10.10:13062 ESTABLISHED
783 10.10.10.10:18080 CLOSE_WAIT
493 10.10.10.10:18082 CLOSE_WAIT
109 10.10.10.10:18080 SYN_RECV
17 10.10.10.10:15062 TIME_WAIT
15 10.10.10.10:15062 ESTABLISHEDhttps://stackoverflow.com/questions/36676312
复制相似问题