如何在Mac OS X中删除ps命令中的标题?

时间:2012-07-17 23:17:33

标签: macos bash shell ps

我使用特定的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

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

5 个答案:

答案 0 :(得分:25)

BSD(以及更普遍的POSIX)等效于GNU的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='

就是这样。

如果您确实需要从任意命令中删除第一行,那么尾部就可以轻松实现:

ps -p 747 -o '%cpu,%mem' | tail +2

或者,如果你想要完全可移植:

ps -p 747 -o '%cpu,%mem' | tail -n +2

cut命令是基于列的等效于较简单的基于行的命令headtail的等价物。 (如果你确实想要剪切列,它可以工作......但是在这种情况下,你可能不会;首先传递你想要的-o参数更简单,而不是通过额外的和试着把它们剪掉。)

与此同时,我不确定为什么你认为你需要评估一些东西作为echo的参数,当它与直接运行它具有相同的效果时,只会让事情变得更复杂。例如,以下两行是等效的:

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

答案 1 :(得分:8)

使用ps --no-headers

  

--no-headers print no header line at all

或使用:

ps | tail -n +2

答案 2 :(得分:6)

使用awk

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

使用sed

ps -p 747 -o %cpu,%mem | sed 1d

答案 3 :(得分:4)

已经选出了获胜者。 Drats ...

如果您已经在使用-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

答案 4 :(得分:0)

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

ps -Ao pcpu =

相关问题