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.

  • Are you assuming that ps will always list a parent process before a child process? That wouldn't be a valid assumption. – G-Man Sep 9 '16 at 1:11
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}' 
  • 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. – Alberto Rivera Sep 8 '16 at 18:44
  • @AlbertoRivera check my edits. – heemayl Sep 8 '16 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. – Alberto Rivera Sep 8 '16 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 Sep 8 '16 at 18:50

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.