Add leading zeroes to numbers in a file

Hello, I am (trying) to write a script that will check to see how many users are logged on to my machine, and if that number is more than 60 I need to kill off all the oldest sessions that are over 60. So far I have been able to check how many users are on and now I am at the part where I have to actually kill them off. I have chosen to write the idle times for all the logged on users into a file, but I need to add leading zeroes to them in order to properly sort them. How do I do this? the file is /tmp/uidle. This is my code so far:

numusers=$(who -q | grep Total | tr -s " " | cut -d" " -f3)                
echo Total number of users: ${numusers}                                    
if test $numusers -gt 60; then                                             
diff=$(expr $numusers - 60)                                                
echo "There are $diff too many users, killing the $diff oldest users..."   
who -u | sort -k4.2,6 | grep bhb | tr -s " " | cut -d" " -f5 >> /tmp/uidle 
else                                                                       
echo "There are less than 60 users. Exiting"                               
fi                                                                         
exit 1                                                                     

Thanks

This will force to a five-digit field, with leading zero:

> val=123
> valf=$(printf "%.5d" "$val")
> echo $valf
00123

(Was not sure what field you were trying to format.)
By the way, you can sort on a numeric. Try the following command which looks at all files in your directory, lists owner size name, but sorts on size:

>ls -l | tr -s " " | cut -d" " -f3,5,9 | sort -n -k2

wish I would have looked around a little more before posting. This is what helped me out:

awk '{for (i=1; i<NF; i++) $i=sprintf("%02d", $i); print; }' /tmp/uidle

At this point though, I need to reorder the numbers inside the file in descending order. I know how to do it in ascending order with

cat /tmp/uidle | sort -k1

How do I reverse it? Or just sort the opposite way to begin with?

see this example:

ls -l | tr -s " " | cut -d" " -f3,5,9 | sort -rn -k2

displays files in reverse order based on size.
So, for your example:

cat /tmp/uidle | sort -r -k1