以带标题的块分组的行中的总和数(使用Bash和AWK)

时间:2016-08-29 09:04:52

标签: linux bash shell awk sum

假设我有以下示例输出:

Node hostabc foofoofoo
        1 foo
        1 ...
        1 ...
        1 ...
        1 ...
        5 ...
Node hostcde ...
        1 ...
        10 ...

如何获取每个主机的数字总和(不使用临时文件,仅使用Bash和AWK)?

例如:

hostabc     10
hostcde     11

2 个答案:

答案 0 :(得分:3)

您可以使用以下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]
    }
}

答案 1 :(得分:3)

$ awk '/^Node/{if(sum)print sum;printf "%s ", $2; sum=0;next} {sum+=$1} END{print sum}' file
hostabc 10
hostcde 11

/^Node/ {            # process Node starting lines
    if(sum)          # won't print sum (empty line) at the beginning
        print sum  
    printf "%s ", $2 # print the host name beforehand
    sum=0            # reset sum
    next             # no need to process further on Node records
}
{
    sum+=$1          # sum
} 
END {
    print sum        # print after the last line also
}