0

I would like to parse the output of ps, to get any field using awk. It seems that ps separate the fields by whitespaces, but the values in COMMAND field usually have whitespaces.

Is there a way to tell ps to use some distinctive field separator in its output? I haven't found one in ps manpage.

If not, what can I do to get the values in a field? Thanks.

3

You can explicitly specify your own field separator in the format string argument when utilizing a printf() style user-defined output:

$ ps -o '%p,%a,%c,%y'
  PID,COMMAND                    ,COMMAND        ,TTY
15742,ps -o %p,%a,%c,%y          ,ps             ,pts/6
24719,-su                        ,bash           ,pts/6
  • This is version-specific. If you're on MacOS (Darwin), the %xs aren't available. – Michael Oct 10 at 13:58
1

You can first replace multiple spaces with a single space (or any other character). See this question on how to accomplish this. Next you can use cut to select the column(s) you want. See also this question.

  • Thanks. Does ps always separate two fields by more than one whitespaces? Does a value under COMMAND never contain more than one consecutive whitespaces? – Tim Dec 4 '18 at 21:15
  • Not sure about that one. – Tommiie Dec 4 '18 at 21:16
1

You could make use of the fact that a shell read places ALL residual fields into the last variable, and print COMMAND last.

ps -eo pid,cmd,tty,args | while read PID CMD TTY ARG; do echo $PID $CMD $TTY $ARG; done

You can convey $ARG to awk, or else concatenate $4 ... $NF within awk when reading the ps output directly

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.