一个用于在Kubernetes表格中求和数字的Bash命令?

huangapple go评论71阅读模式
英文:

A bash command to sum up the numbers in a Kubernetes table?

问题

使用Kubernetes中的"k top pods -A"命令获取CPU使用情况和内存后,是否有办法使用bash命令将这些列求和?或者由于单位的原因,它们无法转换为数字?查看图片描述
我想要能够得到这两列的总和,是否有一个可以做到这一点的bash命令?我似乎无法弄清如何使用awk来做到这一点。
我尝试了awk '{s+=$1}END{print s}', 但我无法真正弄清楚。终端在那之后就停止接受输入,也没有输出任何内容。感谢帮助!谢谢!

英文:

After using k top pods -A in Kubernetes to get CPU usage and memory, is there any way to sum up those columns with a bash command? Or is it not possible for them to be converted to numbers because of the units? enter image description here
I'd like to be able to get the sum of both of these columns, is there a bash command that could do this? I can't seem to figure out how to use awk to do it.
I tried awk '{s+=$1}END{print s}', I couldn't really figure it out. The terminal just stopped taking input after that and didn't output anything. Would appreciate help, thanks!

答案1

得分: 0

我从未使用过Kubernetes,但一些搜索显示输出确实看起来像这样(这不是您的屏幕截图所显示的内容):

NAMESPACE            NAME                                                        CPU(cores)   MEMORY(bytes)   
kube-system          coredns-558bd4d5db-k7mfl                                    8m           11Mi            
kube-system          coredns-558bd4d5db-qwrrk                                    8m           12Mi

根据我所做的有限研究,不清楚单位是否总是 m(毫单位)和 Mi(兆字节)?如果这些是唯一的单位后缀,那么可以简单地忽略它们。由于在Awk中将字符串转换为数字会忽略最后一个数字之后的任何字符,因此您无需做任何操作。

BEGIN {
    cpu = 0
    mem = 0
}
NR == 1 { next }
{
    cpu += $3
    mem += $4
}
END {
    print cpu, mem
}

对于上面的示例数据,这将打印 16 23。如果单位后缀可以是其他字符串,您将需要测试出现的后缀并对数字应用适当的缩放因子。

英文:

I've never used Kubernetes but some Googling shows that the output really looks like this (which is not what your screen grab showed):

NAMESPACE            NAME                                                        CPU(cores)   MEMORY(bytes)   
kube-system          coredns-558bd4d5db-k7mfl                                    8m           11Mi            
kube-system          coredns-558bd4d5db-qwrrk                                    8m           12Mi            

From the limited research I did it is not clear if the units are always m (milliunits) and Mi (megabyte?). If those are the only unit suffixes then simply ignore them. Since converting a string to a number in Awk ignores any characters after the last digit you don't have to do anything.

BEGIN {
    cpu = 0
    mem = 0
}
NR == 1 { next }
{
    cpu += $3
    mem += $4
}
END {
    print cpu, mem
}

For the example data above this will print 16 23. If the unit suffix can be other strings you will need to test which suffix is present and apply an appropriate scaling factor to the number.

huangapple
  • 本文由 发表于 2023年7月14日 06:23:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/76683610.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定