格式化'ps'命令输出,不带空格


11

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

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

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

如何删除空格?

Answers:


10

从手册页:

-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

您介意选择此作为“已接受的答案”吗?@ jeff-schaller
Felipe Alvarez

5

由于前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"

2

您可以使用sedps。所以您想要的是这里:-

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

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


正如我提到的那样,我相信我只选择了一个可以,放在结尾的列,但是,此解决方案,将从该列中删除我不想要的列。
猎豹2014年

查看生成的输出,并告诉我您是否认为这是理想的:)尤其要注意command列。
2014年

那将与相同tr ' ' ,。您可能想要tr -s ' ' ,在这里。
斯特凡Chazelas
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.