I need to parse

0 R username+ 13790 13743  0  80   0 - 28162 -      19:07 pts/0    00:00:00 grep --color=auto pm2
4 S root     25197     1  0  80   0 - 237119 ep_pol Apr05 ?       00:00:32 node /usr/local/lib/node_modules/pm2/bin/pm2

type of output and find the PID for the /usr/local/lib/node_modules/pm2/bin/pm2 process.

so far I have

PROCESS_ID=$(ps -elf | grep pm2 | grep -v grep | awk 'FNR<2{print $4}')

but this only get's the PID for the first line. There's no guarantee what line the correct PID will be, as the upstart program sometimes shows 2-3 results for this grep. I need a way to filter which line to read to awk I guess, since the desired line will only ever be there one at a time. Any help appreciated

  • 1
    Look up pgrep command - it should be much simpler (single command) – Marek Rost Apr 7 '17 at 19:18

Take a look at pgrep:

pgrep -f /usr/local/lib/node_modules/pm2/bin/pm2

awk can be filtered by starting the expression with /regex/

I changed

ps -elf | grep pm2 | grep -v grep | awk 'FNR<2{print $4}'


ps -elf | grep pm2 | grep -v grep | awk '/node_modules/FNR<2{print $4}'

and it worked. You can also search for longer path by escaping slashes:

ps -elf | grep pm2 | grep -v grep | awk '/\/lib\/node_modules/FNR<2{print $4}'

also works

As terrifying as awk is this article was very easy http://www.tecmint.com/use-linux-awk-command-to-filter-text-string-in-files/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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