next up previous contents
Next: Counting number of lines Up: More shell script examples Previous: Replacing a word in   Contents

Counting files greater than a certain size

For the current directory we want to count how many files exceed a given size. For example, saying countsize 100, counts how many files are greater than or equal to 100K size.

#!/bin/sh
# others/countsize

case $# in
0) echo 'Usage: ' $prog '<size in K>'; exit 1;;
esac

limit=$1
count=0
for f in *
do
    if test -f $f
    then
                size=`ls -s $f| awk '{print $1}'`
                if  test $size -ge $limit
                then
                        count=$[count+1]
                        echo $f
                fi
        fi
done
echo $count "files bigger than " $limit"K"

For each selected file, the first if checks if it is a regular file. The we use the command ls -s $f | awk 'print $1', which prints the size of the file in Kilobytes. We pipe the output of the ls to awk, which is used to extract the first field (the size). Then we put this pipe combination in back-quotes to evaluate and store the result in the variable size. The if statement then tests if the size is greater than or equal to the limit. If it is, then we increment the count variable. Note the use of the square brackets to perform arithmetic evaluation.



Amit Jain 2006-11-20