假设我有以下示例输出:
Node hostabc foofoofoo
1 foo
1 ...
1 ...
1 ...
1 ...
5 ...
Node hostcde ...
1 ...
10 ...
如何获得每个主机的数字总和(不使用临时文件,仅使用 Bash 和 AWK)?
例如:
hostabc 10
hostcde 11
最佳答案
您可以使用以下 awk
命令:
awk '/^Node/{n=$2;next}{t[n]+=$1}END{for(n in t){print n,t[n]}}' file
更好地解释为多行脚本:
# If the line starts with 'Node'
/^Node/ {
# Set n(ame) to the value of the second field
n=$2
# No further actions on this line
next
}
{
# Add the value of the first field to t(otals)[n(name)]
t[n]+=$1
}
# Once the end of input has been reached
END{
# Iterate trough t(otals) keys
for(n in t) {
# Print the total along with the name
print n,t[n]
}
}
关于linux - 在带有标题的 block 中分组的行中的数字总和(使用 Bash 和 AWK),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39202326/