如何获得所有正在运行的进程id?

我知道

ps ax 

返回pid

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

我只需要清理这些string,但是我不能用sed来完成,因为我无法写出正确的正则expression式。 你可以帮帮我吗?

使用ps输出格式:

ps -A -o pid

输出格式的命令是最好的select。 o选项控制输出格式。 我列出了下面的一些参数,其余部分请参阅“man ps”(使用多个参数将是-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或Cut会更好地得到列:
一般来说,你不会想要一个正则expression式来select第一列,你可能想要通过pipe道剪切或awk剪切第一列,如:

 ps ax | awk '{print $1}' 

正则expression式是一个选项,如果不是最好的:
如果你使用正则expression式,它可能是这样的:

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

$ 1仅打印括号中匹配的内容。 ^锚定到行的开始。 空格星号意味着在数字之前允许可选的空格字符。 [0-9] +表示一个或多个数字。 但我不会推荐这个特定任务的正则expression式,看看为什么? 🙂

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

使用-o开关来输出一个cust格式

 ps -o pid 

使用sed的坏方法,正如你明确要求的那样

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