19

I've got supervisor's status output, looking like this.

frontend                         RUNNING    pid 16652, uptime 2:11:17
nginx                            RUNNING    pid 16651, uptime 2:11:17
redis                            RUNNING    pid 16607, uptime 2:11:32

I need to extract nginx's PID. I've done it via grep -P command, but on remote machine grep is build without perl regular expression support.

Looks like sed or awk is exactly what I need, but I don't familiar with them.

Please help me to find a way how to do it, thanks in advance.

cleg
  • 4,862
  • 5
  • 35
  • 52

6 Answers6

24
sed 's/.*pid \([0-9]*\).*/\1/'
reko_t
  • 55,302
  • 10
  • 87
  • 77
  • 3
    In order for this to work you'll need to specify the option to enable extended regular expressions. This is usually '-r' (GNU sed) or '-E' (BSD sed). See: https://stackoverflow.com/questions/16637799/sed-error-invalid-reference-1-on-s-commands-rhs – Joey J Apr 03 '19 at 20:43
8

Using AWK alone:

awk -F'[ ,]+' '{print $4}' inputfile
Dennis Williamson
  • 346,391
  • 90
  • 374
  • 439
7
$ cat $your_output | sed -s 's/.*pid \([0-9]\+\),.*/\1/'
16652
16651
16607
Stephen
  • 47,994
  • 7
  • 61
  • 70
6

Solution with awk and cut

vinko@parrot:~$ cat test
frontend                         RUNNING    pid 16652, uptime 2:11:17
nginx                            RUNNING    pid 16651, uptime 2:11:17
redis                            RUNNING    pid 16607, uptime 2:11:32
vinko@parrot:~$ awk '{print $4}' test | cut -d, -f 1
16652
16651
16607

for nginx only:

vinko@parrot:~$ grep nginx test | awk '{print $4}' | cut -d, -f 1
16651
Vinko Vrsalovic
  • 330,807
  • 53
  • 334
  • 373
  • there's no need to use awk + cut + grep. Just awk will do the job. `awk -F"," '/nginx/{print $1}' file` – ghostdog74 Jun 18 '10 at 14:05
  • @ghostdog74: your command outputs "nginx RUNNING pid 16651". The correct awk only solution is in the answer by Dennis (http://stackoverflow.com/questions/3045493/parse-string-with-bash-and-extract-number/3045718#3045718), using -F '[ ,]+' instead of -F ',' – Vinko Vrsalovic Jun 18 '10 at 19:07
  • @vinko, its either that, or just use gsub() to get rid of the comma for awk versions that does not support multiple field delimiters. I am just highlighting the point that awk can do the job and there's no need to use other tools. – ghostdog74 Jun 19 '10 at 15:58
  • @ghostdog74: Right, you can do it with awk only. – Vinko Vrsalovic Jun 19 '10 at 19:29
2

Take a look at pgrep, a variant of grep specially tailored for grepping process tabless.

Ether
  • 53,118
  • 13
  • 86
  • 159
1

assuming that the grep implementation supports the -o option, you could use two greps:

output \
  | grep -o '^nginx[[:space:]]\+[[:upper:]]\+[[:space:]]\+pid [0-9]\+' \
  | grep -o '[0-9]\+$'
intuited
  • 23,174
  • 7
  • 66
  • 88