1

I am fairly new to awk. I wanted to create a quick command to find the process number of my parent Nodejs process. I came out with this:

ps aux | awk '/node/' | awk 'NR == 1 {print $1}'

However, I think there should be a way to combine both awk commands into a single one. What is a more compact way of writing this?

EDIT:

While pgrep is more suitable for this task in specific, I still would like to know how to search and print the first row with awk.

1
  • Are you assuming that ps will always list a parent process before a child process? That wouldn't be a valid assumption. Commented Sep 9, 2016 at 1:11

1 Answer 1

1

You don't need any text processing on the output of ps, there is a dedicated tool for exactly this purpose, called pgrep.

Simply do:

pgrep node

instead of the string node, you can use a Regex pattern.

For a detailed output with process name:

pgrep -l node

To get the command name too:

pgrep -a node

Check man pgrep to get more idea.


if you insist on using awk on ps, and merging two awks as one, do:

ps aux | awk '/node/ {print $1; exit}' 
4
  • Thanks a lot. This does exactly what I need. However, I still would like to know how to search and print the first row with awk. Commented Sep 8, 2016 at 18:44
  • @AlbertoRivera check my edits.
    – heemayl
    Commented Sep 8, 2016 at 18:46
  • Thank you very much for your time. I will accept your answer. However, if that's OK with you, I would like to know how to print X row after searching. Say, I want to kill the children node process instead of the parent one. Commented Sep 8, 2016 at 18:48
  • @AlbertoRivera There are so many ways to do that but again you are doing it wrong, you should look at pkill/killall.
    – heemayl
    Commented Sep 8, 2016 at 18:50

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .