#!/bin/bash                                                

# set DIRNAME to 1 to display the VM directory name instead of the VMX filename
DIRNAME=1                                                                      
DELAY=2                                                                        

clear

while (true); do

 # this is the result in a flat list of value pairs (PID, %CPU)
 # we must use -n2 as the first output of atop is allways bogus 
 RESULT=`atop -d 1 -n 2 -C 2>/dev/null | tail -n 19 | grep vmx| sed 's/^\ *//g' |awk '{print $1 " "  $5 }'`                                                                           

 # let's insert the (PID, CPU) value pairs into lines of an array of strings and add the cmdline                                                                                      
 j=0                                                                                       
 flag=0                                                                                    
 for i in $RESULT; do                                                                      
   LINES[$j]="${LINES[$j]} $i"                                                             
   if [ $flag -eq 1 ]; then                                                                
     PID=`echo ${LINES[$j]} | awk '{print $1'}`                                            
     CMDLINE=`cat /proc/$PID/cmdline`                                                      
     AUX=`echo $CMDLINE | awk -F= '{print $NF}' | sed 's/^[0-9]*\//\//g'`                  
     if [ $DIRNAME -ne 1 ]; then                                                           
         VMNAME=`basename "$AUX"`                                                          
     else                                                                                  
         AUX2=`dirname "$AUX"`                                                             
         VMNAME=`echo $AUX2 | awk -F/ '{print $NF}'`                                       
     fi                                                                                    
     # the VMNAME goes to a separate array as it may have whitespace (doh...)              
     NAMES[$j]="$VMNAME"                                                                   
     let j=$j+1
   fi
   let flag=1-$flag
 done

 # let's display the result
 top -d 1 -n 1  |head -n 4
 echo
 for i in `seq 0 $(( j-1 ))`; do
   # we need to quote $NAMES as there may be whitespace and printf complains
   printf "%5d %4s %s" ${LINES[$i]} "${NAMES[$i]}"
   echo
   LINES[$i]=""
   NAMES[$i]=""
 done

 echo -e "\nPress Ctrl+C to exit"
 sleep $DELAY

done

