Find the pids of the processes you want to monitor and then use the -p option which allows you to provide a list of pids to the top command.
Example:
top -p 18884 -p 18892 -p 18919
PID USER PRI NI SIZE RSS SHARE STAT %CPU %MEM TIME CPU COMMAND
18884 user 25 0 672M 95M 9476 S 0.0 1.1 0:02 1 java
18892 user 25 0 2280M 123M 12252 S 0.0 1.5 0:05 1 java
18919 user 22 0 1492M 198M 28708 S 0.0 2.4 0:07 1 java
(I believe you can also pass in a comma-separated list.)
I came here looking for the answer to this on OSX. I ended up getting what I wanted with bash and awk:
topfiltered() {
[[ -z "$1" ]] && return
dump="/tmp/top_dump"
rm -f "$dump"
while :; do
clear
[[ -s "$dump" ]] && head -n $(( $LINES - 1 )) "$dump"
top -l 1 -o cpu -ncols $(( $COLUMNS / 8 )) | awk -v p="$(pgrep -d ' ' $@)" '
BEGIN { split(p, arr); for (k in arr) pids[arr[k]]=1 }
NR<=12 || ($1 in pids)
' >"$dump"
done
}
I loop top in logging mode and filter it with awk, building an associative array from the output of pgrep. Awk prints the first 12 lines, where line 12 is the column headers, and then every line which has a pid that's a key in the array. The dump file is used for a more watchable loop.
Using the approach mentioned in the answer by Rick Byers:
top -p `pgrep java | paste -sd "," -`
but I had more than 20 processes running so following command can be helpful for someone who encounter a similar situation.
top -p `pgrep java | head -n 20 | paste -sd "," -`
pgrep gets the list of processes with given name - java in this case. head is used to get first 20 pids because top cannot handle more than 20 pids when using -p argument. Finally paste joins the list of pids with ','.
You can control the process name you are looking for in the above command and the number of processes with that name you are interested to watch. You can ignore the head -n 20 part if the number of your processes with the given name is less than 20.
You need to feed the output of pgrep {proc_name} to top -pid {pid_No}. The problem with top -pid is that it expects -pid before each pid you want to monitor.
On Mac in zsh I can handle this problem e.g. like that:
top `pgrep proc_name | awk '{printf " -pid %d",$1}'`
It's not ideal too, because pgrep looks for substrings in process names. E.g. pgrep dd can return results for icdd, hidd, cloudd etc. The option
pgrep -x should return the exact matches only (like grep -w). But it doesn't work for me in Mac Terminal, although it does in Ubuntu virtual machine.