开发者

Selecting one value per row - awk

I have a file formatted like:

10.0.0.1        87.220.150.64   131
10.0.0.1        87.220.172.219  131
10.0.0.1        87.220.74.162   131
10.0.0.1        87.220.83.17    58
10.0.0.1        87.220.83.17    58
1.160.138.209   10.0.0.249      177
1.160.138.209   10.0.0.249      354
1.160.138.249   10.0.0.124      296
1.160.139.125   10.0.0.252      129
1.160.139.207   10.0.0.142      46

The first and the second columns are IP addresses and the third one is the bytes transferred between IPs. I have to count how many bytes each 10.something IP-address has sent or received.

I used following awk program to calculate how many bytes each IP had sent but I cant figure out how to edit it to also calculate the received bytes.

awk开发者_如何学JAVA '{ a[$1 " " $2] += $3 } END { for (i in a) { print i " " a[i] } }' input.txt | sort -n


This doesn't distinguish between bytes sent and bytes received.

# bytes-txrx.awk -- print bytes sent or received by each 10.* ip address.
# Does not guard against overflow.
#
# Input file format:
# 10.0.0.1        87.220.150.64   131
# 10.0.0.1        87.220.172.219  131
# 10.0.0.1        87.220.74.162   131
# 10.0.0.1        87.220.83.17    58
# 10.0.0.1        87.220.83.17    58
# 1.160.138.209   10.0.0.249      177
# 1.160.138.209   10.0.0.249      354
# 1.160.138.249   10.0.0.124      296
# 1.160.139.125   10.0.0.252      129
# 1.160.139.207   10.0.0.142      46
#
$1 ~ /^10\./ {a[$1] += $3;}
$2 ~ /^10\./ {a[$2] += $3;}
END {
  for (key in a) {
    print key, a[key];
  }
}

$ awk -f test.awk test.dat
10.0.0.1 509
10.0.0.252 129
10.0.0.249 531
10.0.0.142 46
10.0.0.124 296


Just sort by column 2 and you have it:

$ awk '{ a[$1 " " $2] += $3 } END { for (i in a) { print i " " a[i] } }' input.txt | sort -n -k 2

But your description does not match the calculation. You do not calculate how much an IP sends. You calculate how much is send from A to B. And the amount A sends it the same as B receives.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜