views:

90

answers:

6

Hello

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.

+1  A: 
$ cat $your_output | sed -s 's/.*pid \([0-9]\+\),.*/\1/'
16652
16651
16607
Stephen
This is known as a UUOC (Useless use of cat)
mikerobi
@mikerobi : that was just an example of how to pipe stuff into the command... he didn't say how he had his output... but whatever.
Stephen
+2  A: 
sed 's/.*pid \([0-9]*\).*/\1/'
reko_t
+3  A: 

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
the final cleanup of the comma can be done with:tr -d ','
Marcin
Thank you, @Marcin
Vinko Vrsalovic
there's no need to use awk + cut + grep. Just awk will do the job.`awk -F"," '/nginx/{print $1}' file`
ghostdog74
@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
@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
@ghostdog74: Right, you can do it with awk only.
Vinko Vrsalovic
+2  A: 

Using AWK alone:

awk -F'[ ,]+' '{print $4}' inputfile
Dennis Williamson
+1  A: 

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
+1  A: 

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

Ether