How to get all running process ids only?

Solution 1:

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? :-)

Solution 2:

ps ax | awk '{ print $1; }'

Solution 3:

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#'