14

我使用特定的 ps 命令,即

ps -p <pid> -o %cpu, %mem

这给了我一个像

 %CPU %MEM
 15.1 10.0

我想要做的只是打印这些数字,如 15.1 和 10.0 没有标题。我尝试使用 'cut' 。但它似乎适用于每一行。

IE

echo "$(ps -p 747 -o %cpu,%mem)" | cut -c 1-5

给出类似的东西

 %CPU
  8.0

如何获得没有标题的数字?

4

5 回答 5

29

GNU 的 BSD(以及更普遍的 POSIX)等价物ps --no-headers有点烦人,但是,从手册页:

 -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 "$(ps -p 747 -o %cpu,%mem)" | cut -c 1-5
ps -p 747 -o %cpu,%mem | cut -c 1-5
于 2012-07-18T00:16:46.730 回答
8

使用awk

ps -p 747 -o %cpu,%mem | awk 'NR>1'

使用sed

ps -p 747 -o %cpu,%mem | sed 1d
于 2012-07-17T23:22:36.100 回答
8

使用ps --no-headers

--no-headers print no header line at all

或使用:

ps | tail -n +2
于 2012-07-17T23:45:35.230 回答
4

已经选择了获胜者。德拉斯...

如果您已经在使用该-o参数,则可以通过在名称和列名称后面加上等号来指定要打印的特定列的标题。如果您输入一个空字符串,它将不打印任何标题:

使用标准标题(如您所见):

$ ps -p $pid -o%cpu,%mem
 %CPU %MEM
  0.0  0.0

使用自定义标题(只是为了向您展示它是如何工作的):

$  ps -p $pid -o%cpu=FOO,%mem=BAR
  FOO  BAR
  0.0  0.0

使用空标题(注意它甚至不打印空行):

$ ps -p $pid -o%cpu="",%mem=""
 0.0   0.0
于 2012-07-18T00:20:20.287 回答
0

您可以使用以下命令,而无需添加 pcpu="",它对我有用:

ps -Ao pcpu=

于 2020-12-17T15:02:12.193 回答