linux - 在带有标题的 block 中分组的行中的数字总和(使用 Bash 和 AWK)

标签 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

最佳答案

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

相关文章:

arrays - bash:如何使用一个数组创建另一个数组?

c - 为什么编译成功后执行c程序没有输出?

c - Makefile 中的自动变量未正确扩展

linux - 如何使用 m68k-uclinux-gcc 设置堆栈大小?

mysql - 试图使RmySQL工作,但不了解bash的导出或文件系统约定

linux - 为什么这个示例脚本在 token 附近不断输出错误?

linux - jq 是否可以在设置新值时使用已删除的值?

linux - 是否有任何应用程序/编辑器可以跟踪文件中发生的更改并显示它们?

c - Linux 设备驱动程序中的静态函数?

linux - 从 shell 中的 ssh 调用获取局部变量