quick tips - awk grep pipe xargs

edited March 2022 in LES Talk

Written by Anthony Smith, 7 July 2020
Article was migrated from WordPress to Vanilla in March 2022

In this post we will be looking at running top in batch mode, looking for a string with grep, grabbing the process id's with awk and sending the process id's to be processed by another command with xargs.

For speed, I have just set up a quick VPS and installed apache.

top in batch mode

top -b -n1

This command with do as it suggests run top in batch mode with the -b switch, the -n1 tells it to run 1 time, -n5 would be 5 times.

Looking for a string with grep

We can pipe the output of top in batch mode to grep to search for a string, in this case I will look for the apache2 processes.

top -b -n1 | grep apache

If we want to monitor these, for example, to see how much cpu time they are using we can up the number of times the batch mode in top runs:

top -b -n5 | grep apache

This will run 5 times because of the -n5

This would be useful over the more commonly used watch command if you wanted to log the output to a file, for example:

top -b -n5 | grep apache2 >logfile

Adding awk into the mix

Now how about if we want to grab just the process id's from the output? for that we add awk into the mix:

top -b -n1 | grep apache2 | awk '{print $1}'

This gives us just the pids of the apache2 processes, the $1 in the awk print command prints the first column only, obviously if you want more columns you can add more, for example:

top -b -n1 | grep apache2 | awk '{print $1, $12}'

Taking an action with xargs

Ok so what if we want to add some sort of action to all of this, for example, we may want to kill all apache2 processes. (obviously you can use the killall command however this is just for the sake of the example) for this we can add xargs into the mix

top -b -n1 | grep apache2 | awk '{print $1}' | xargs kill

As we can see in the image above, top has been run in batch mode once, the output piped to grep to search for the apache2 string that output is then piped into awk which has printed only the process id's which have then been piped to xargs which has then ran the kill command on them 1 by 1, then searching for apache2 processes again they are gone confirming they were killed.

The kill command can be substituted for any other command for example if you are running containers on an OpenVZ server and spot a bunch of suspect processes you can run them through vzpid to get the container id's of processes under a particular name to find the owner of those processes.

Sign In or Register to comment.