格式化“ps”命令输出,不含空格

格式化“ps”命令输出,不含空格

我有以下ps命令来获取所有正在运行的进程的特定属性以及一些属性:

ps --no-headers -exo "uname,ppid,pid,etime,%cpu,%mem,args"

我希望将其格式化为 CSV,以便我可以解析它。请注意,我已将 args 放在末尾以使解析变得容易;我认为,其他任何专栏中都不存在遗嘱 - 如果我错了,请纠正我。

如何删除空格?

答案1

从手册页:

-o format       user-defined format.
                format is a single argument in the form of a blank-separated or comma-separated list, which offers a
                way to specify individual output columns. The recognized keywords are described in the STANDARD FORMAT
                SPECIFIERS section below. Headers may be renamed (ps -o pid,ruser=RealUser -o comm=Command) as
                desired. If all column headers are empty (ps -o pid= -o comm=) then the header line will not be
                output. Column width will increase as needed for wide headers; this may be used to widen up columns
                such as WCHAN (ps -o pid,wchan=WIDE-WCHAN-COLUMN -o comm). Explicit width control
                (ps opid,wchan:42,cmd) is offered too. The behavior of ps -o pid=X,comm=Y varies with personality;
                output may be one column named "X,comm=Y" or two columns named "X" and "Y". Use multiple -o options
                when in doubt. Use the PS_FORMAT environment variable to specify a default as desired; DefSysV and
                DefBSD are macros that may be used to choose the default UNIX or BSD columns.

所以尝试:

/bin/ps -o uname:1,ppid:1,pid:1

答案2

由于前 6 个字段不应包含空白字符(除非您允许在用户名中使用它们),因此您可以对输出进行后处理:

ps --no-headers -exo "uname,ppid,pid,etime,%cpu,%mem,args" | sed '
  s/[\"]/\\&/g
  s/  */,/;s/  */,/;s/  */,/;s/  */,/;s/  */,/;s/  */,"/
  s/$/"/'

"这里引用使用 转义s 和\s后的最后一个字段 (args) \

产生如下输出:

stephane,3641,3702,10-00:20:24,0.1,0.3,"some cmd,and,args... VAR=foo\"bar"

答案3

您可以sed与 一起使用ps。所以你想要的就在这里:-

ps --no-headers -exo "uname,ppid,pid,etime,%cpu,%mem,args" | sed 's/\ /,/g'

但我想知道它是否有用,因为ps它本身的输出有很多,.

相关内容