39

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?

darxsys
  • 1,560
  • 4
  • 20
  • 34

4 Answers4

62

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-
Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
17

Is there any particular reason for using cut?

I guess this will do what you want:

ps -eopid,uid,cmd
Sylvain Kalache
  • 381
  • 2
  • 8
  • I'm just a beginner so trying what I think of. Should have read man pages in more detail. Thanks – darxsys Mar 26 '13 at 17:46
  • 3
    Not every Unix provides these options to `ps`, while every Unix provides `cut`. – sfstewman Mar 26 '13 at 17:53
  • Both `-e` and `-o` are specified by POSIX. [The spec](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/ps.html) does mention some of the difficulties of standardizing `ps` given the large differences between the pre-existing BSD and System V implementations. – chepner Mar 26 '13 at 18:16
  • This was helpful to me because I need to grep output of ps before cut down to just pid. – GrnMtnBuckeye Jan 06 '16 at 21:37
  • putting a space between eo and pid makes it more readable and that is also how it is mentioned in the man pages. – infoclogged Mar 25 '17 at 11:19
16

You can use awk to clean up your command, like so:

ps -L u n | awk '{ print $1,$2,$13 }'
Nathan Adams
  • 161
  • 3
-1

The question is what to do once you have a list. I find cut kludgy, so instead of cut I pass the list to a while read loop. "While read" recognizes non-blank values on a line, so in this example, "a" is the first value, "b" is the second and "c" is the rest of the line. I am only interested in the first 2 values, process owner and process ID; and I basically abuse the case statement rather than use an "if". (Even though grep filtered, I don't want to kill processes where the owner name might be embedded elsewhere in the line)

ps -ef | grep owner | grep -v grep | while read a b c; 
do 
 case $a in 
  "owner")
     kill -9 $b  
   ;; 
 esac; 
done
Pat
  • 1