I know that

ps ax

returns the pids

1 ?        Ss     0:01 /sbin/init
2 ?        S<     0:00 [kthreadd]
3 ?        S<     0:00 [migration/0]

All I need is to clean those strings, but I couldn't do it with sed because I couldn't write the proper regex. Could you help me?

link|improve this question

74% accept rate
feedback

3 Answers

up vote 7 down vote accepted

Use ps Output Formatting:

ps -A -o pid

Output formatting of the command is the best option. The o option controls the output formatting. I listed some of arguments below below, see 'man ps' for the rest ( to use multiple it would be -o pid,cmd,flags).

KEY   LONG         DESCRIPTION
   c     cmd          simple name of executable
   C     pcpu         cpu utilization
   f     flags        flags as in long format F field
   g     pgrp         process group ID
   G     tpgid        controlling tty process group ID
   j     cutime       cumulative user time
   J     cstime       cumulative system time
   k     utime        user time
   o     session      session ID
   p     pid          process ID

Awk or Cut Would be Better to get Columns:
Generally you wouldn't want a regex for selecting the first column, you would want to pipe it to cut or awk to cut out the first column like:

ps ax | awk '{print $1}'

Regex is an Option, if not the best:
If you were to use regex, it could be something like:

ps ax | perl -nle 'print $1 if /^ *([0-9]+)/'

$1 prints only what was matched in the parenthesis. ^ anchors the to the start of the line. Space asterisk means allow for optional space characters before the number. [0-9]+ means one or more digits. But I wouldn't recommend regex for this particular task, see why? :-)

link|improve this answer
thanks! but the regular expression would be a great addition, if anyone could contribute with a second answer – Jader Dias Aug 12 '09 at 18:33
1  
really, use awk. – David Pashley Aug 12 '09 at 18:42
Pay attention, the regex would not match the initial spaces eventually being before small pids. Moreover a pid should be make of a digit at least, not zero (you should use + and not *) – AlberT Aug 12 '09 at 18:47
AlberT, oh good point, Didn't see that they were right justified. That is why I said regex is not the best I guess, will fix :-) – Kyle Brandt Aug 12 '09 at 18:50
I can't argue how to use cut, by means of the initial spaces of course. Can you point out to me how to use cut? Just for the sake of curiosity :) – AlberT Aug 12 '09 at 19:06
show 2 more comments
feedback
ps ax | awk '{ print $1; }'
link|improve this answer
feedback

Use the -o switch to have a cust format output

ps -o pid

The bad way using sed, as you explicitly asked may be

ps -ax | sed 's#^\( *[0-9]\+\) .*$#\1#'
link|improve this answer
feedback

Your Answer

 
or
required, but never shown

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