我使用特定的 ps 命令,即
ps -p <pid> -o %cpu, %mem
这给了我这样的结果
%CPU %MEM
15.1 10.0
我只想打印这些数字,如 15.1 和 10.0,不带标题。我尝试使用 'cut' 。但它似乎适用于每一行。
即
echo "$(ps -p 747 -o %cpu,%mem)" | cut -c 1-5
给出类似的东西
%CPU
8.0
如何只获取没有标题的数字?
最佳答案
与 GNU 的 ps --no-headers
等效的 BSD(以及更普遍的 POSIX)有点烦人,但是,来自手册页:
-o Display information associated with the space or comma sepa- rated list of keywords specified. Multiple keywords may also be given in the form of more than one -o option. Keywords may be appended with an equals (`=') sign and a string. This causes the printed header to use the specified string instead of the standard header. If all keywords have empty header texts, no header line is written.
所以:
ps -p 747 -o '%cpu=,%mem='
就是这样。
如果您确实需要从任意命令中删除第一行,tail 可以让这变得简单:
ps -p 747 -o '%cpu,%mem' | tail +2
或者,如果您想要完全便携:
ps -p 747 -o '%cpu,%mem' | tail -n +2
cut
命令是一种基于列的命令,相当于更简单的基于行的命令 head
和 tail
。 (如果你真的想削减列,它会起作用......但在这种情况下,你可能不会;首先将你想要的 -o
参数传递给 ps 比传递额外内容并尝试将它们剪掉。)
与此同时,我不确定为什么您认为需要将某些东西作为 echo 的参数进行评估,而这与直接运行它具有相同的效果,只是让事情变得更复杂。例如,下面两行是等价的:
echo "$(ps -p 747 -o %cpu,%mem)" | cut -c 1-5
ps -p 747 -o %cpu,%mem | cut -c 1-5
关于macos - 如何摆脱 Mac OS X 中 ps 命令中的 header ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11532188/