macos - 如何摆脱 Mac OS X 中 ps 命令中的 header ?

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

如何只获取没有标题的数字?

最佳答案

与 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 命令是一种基于列的命令,相当于更简单的基于行的命令 headtail。 (如果你真的想削减列,它会起作用......但在这种情况下,你可能不会;首先将你想要的 -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/

相关文章:

linux - 获取 Linux 接口(interface)上传入/传出带宽速度的快照?

python - 需要帮助从 python 项目中的 pygtk GUI 实时捕获 STDOUT

bash - 我应该将 shell 函数定义为函数 x( ) 还是仅定义为 x( )?

BASH:OSX 中的 $(date) 结果为 "Illegal variable name"

macos - 更改 "last opened"日期

macos - 安装 pylint OSX 忽略可执行文件

linux - 在不指定字符数限制的情况下检查 shell 脚本中的数字是否为十六进制 [bash]

linux - 使用 AWK 打印除第一列之外的所有列

linux - GNUPLOT:无效的表达?

python - matplotlib 在 mac osx 上挂起并且不显示图形