Unix find average file size

Use wc -c * to get the size of all the files and ls | wc -l to get the number of files. Then just divide one by the other.


A short, general and recursion-friendly variation of Ernstsson's answer:

find ./ -ls | awk '{sum += $7; n++;} END {print sum/n;}'

Or, for example, if you want to impede files above 100 KB from stewing the average:

find ./ -size -100000c -ls | awk '{sum += $7; n++;} END {print sum/n;}'

I found something here:
http://vivekjain10.blogspot.com/2008/02/average-file-size-within-directory.html

To calculate the average file size within a directory on a Linux system, following command can be used:

ls -l | gawk '{sum += $5; n++;} END {print sum/n;}'

This works portably, even on AIX. Outputs average number of bytes for plain files in the specified directory (${directory} in the example below):

find "${directory}" '!' -path "${directory}" -prune -type f -ls | awk '{s+=$7} END {printf "%.0f\n", s/NR}'

No need in counting the number of files yourself. NR is an awk builtin for number of rows.

The '!' -path ${directory} -prune part is a portable way to achieve the equivalent of GNU find -maxdepth 1 by pruning any path that is not the same as the one we start at, thereby ignoring any subdirectories.

Adjust with restrictions on what files to count. For instance, to average all files except *.sh in the current directory, you could add '!' -name '*.sh':

find . '!' -path . -prune -type f '!' -name '*.sh' -ls | awk '{s+=$7} END {printf "%.0f\n", s/NR}'

or to count only *.mp3 and include all subdirectories (remove '!' -path . -prune):

find . -type f -name '*.mp3' -ls | awk '{s+=$7} END {printf "%.0f\n", s/NR}'

Tags:

Unix

Size