Unix find average file size

前端 未结 7 2376
忘掉有多难
忘掉有多难 2020-12-13 09:23

I have a directory with a ton of files I want to find the average file size of these files so something like ls somethinghere whats the average file size of everyth

7条回答
  •  心在旅途
    2020-12-13 10:13

    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}'
    

提交回复
热议问题