Using bash ps and cut together

darxsys picture darxsys · Mar 26, 2013 · Viewed 28.6k times · Source

I need to extract PID, UID and command fields from 'ps' and I have tried it like this:

ps -L u n | cut -f 1,2,13

For some reason, this behaves as there is no cut command whatsoever. It just returns normal ps output. Then, I tried

ps -L u n | tr -s " " | cut -d " " -f 1,2,13 and this returns total nonsense. Then, I tried playing with it and with this:

ps -L u n | tr -s " " | cut -d " " -f 2,3,14

and this somehow returns what I need (almost, and I don't understand why that almost works), except that it cuts out the command field in the middle of it. How can I get what I need?

Answer

Explosion Pills picture Explosion Pills · Mar 26, 2013

ps is printing out space separators, but cut without -d uses the tab character. The tr -s squeezes the spaces together to get more of the separation that you want, but remember that there is the initial set of spaces (squeezed to one) hence why you need to add 1 to each field. Also, there are spaces in the commands for each word. This should work:

ps -L u n | tr -s " " | cut -d " " -f 2,3,14-