我有以下ps
命令来获取所有正在运行的进程的特定属性以及一些属性:
ps --no-headers -exo "uname,ppid,pid,etime,%cpu,%mem,args"
Run Code Online (Sandbox Code Playgroud)
我希望将它格式化为 CSV 以便我可以解析它。注意我把 args 放在最后以方便解析;我不认为 a ,
will 存在于任何其他列中 - 如果我错了,请纠正我。
如何去除空格?
Fel*_*rez 12
从手册页:
-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.
Run Code Online (Sandbox Code Playgroud)
所以尝试:
/bin/ps -o uname:1,ppid:1,pid:1
Run Code Online (Sandbox Code Playgroud)
由于前 6 个字段不应包含空白字符(除非您允许在用户名中使用它们),因此您可以对输出进行后处理:
ps --no-headers -exo "uname,ppid,pid,etime,%cpu,%mem,args" | sed '
s/[\"]/\\&/g
s/ */,/;s/ */,/;s/ */,/;s/ */,/;s/ */,/;s/ */,"/
s/$/"/'
Run Code Online (Sandbox Code Playgroud)
在使用 .s"
和\
s转义后引用最后一个字段(args)\
。
产生如下输出:
stephane,3641,3702,10-00:20:24,0.1,0.3,"some cmd,and,args... VAR=foo\"bar"
Run Code Online (Sandbox Code Playgroud)
您可以sed
与 一起使用ps
。所以你想要的就在这里:-
ps --no-headers -exo "uname,ppid,pid,etime,%cpu,%mem,args" | sed 's/\ /,/g'
Run Code Online (Sandbox Code Playgroud)
但我想知道它是否有用,因为ps
它本身的输出有很多,
.