D
D
DetRyg2022-03-19 23:04:39
bash
DetRyg, 2022-03-19 23:04:39

Function to calculate the average size of a file in a directory in Bash?

We need to write a function to calculate the average size of a file in a directory. In this case, the function should check the directory for existence, and then display the average size of files in the directory. You also need to exclude subdirectories and symbolic links from the calculations.

I hit a dead end, and I can’t go further than this function ...
stat -c '%F %s' /mydir/.* *

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
mc2, 2022-03-22
@mc2

find $1 -type f -ls|awk '{sum+=$7}END{print sum/NR}'

A
Alexander Karabanov, 2022-03-20
@karabanov

#!/bin/bash

# uncomment for debug
#set -x

function get_avg_size() {

  [ ! -d "$1" ] && echo "Directory $1 DOES NOT exists." && exit 1

  sum_size=0
  count=0

  for size in $(LC_ALL=C stat -c '%F %s' $1/* | grep 'regular file' | cut -d ' ' -f 3); do
    let sum_size=$sum_size+$size
    let count=$count+1
  done

  echo "Average file size $(($sum_size/$count))"
}

get_avg_size ~/

Here's an option for you. To a sane state, add yourself.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question