Files
q-tools/files/ext-summary
2019-12-22 13:18:06 +02:00

126 lines
2.5 KiB
Bash
Executable File

#!/bin/bash
function helpexit() {
echo "Display extension sizes and counts"
echo "Returns only the size as number"
echo " --help This help"
echo " -a Disable animation while counting"
exit
}
function filesize() {
# Return a human readable size from integer of bytes
# Usage: filesize 10000
[ "$1" = "0" ] && {
echo "0~B"
return 0
}
awk 'BEGIN{ x = '$1'
split("B kB MB GB TB PB EB ZB", type)
for(i=7;y < 1;i--)
y = x / (2^(10*i))
if (i==-1) { printf( "%d~B", x) }
if (i>-1) { printf( "%0.1f%s", y, type[i+2]) }
}' || return $?
}
function siprefix() {
# Return a SI prefixed string from integer
[ "$1" = "0" ] && {
echo "0~#"
return 0
}
awk 'BEGIN{ x = '$1'
split("# k# M# G# T# P# E# Z#",type)
for(i=7;y < 1;i--)
y = x / (10^(3*i))
if (i==-1) { printf( "%d~#", x) }
if (i>-1) { printf( "%0.1f%s", y, type[i+2]) }
}' || return $?
}
function animate() {
CHARS=( \
'\_(".)_/' \
'\_(.")_/' \
'\_(".)_/' \
'\_(.")_/' \
"\_('')_/" \
'\_(..)_/' \
"\_('')_/" \
"\_('')_/" \
)
i=0
while true; do
sleep 1.5
printf "\r %s\r" "${CHARS[$i]}" >&2
i=$(( (i + 1)%${#CHARS[@]} ))
done
}
function processfolders() {
printf "%8s %8s %-10s\n" \
Size \
Count \
Name
find "$@" -type f \
-printf "%s|%P\n" 2>/dev/null | awk '
BEGIN { FS = "|" }
{
n = split($2, fname, "/");
if (index(fname[n], ".") > 1) {
n = split(fname[n], fsplit, ".");
ext = "."tolower(fsplit[n])
} else {
ext = "N/A"
}
sum[ext] += $1;
count[ext] += 1;
}
END {
for (e in sum) {
print sum[e]"|"count[e]"|"e
}
}' | sort -n -k 1 -t\| | while read line; do
IFS='|' read -r -a array <<< "$line"
printf "%8s %8s %-10s\n" \
$( filesize "${array[0]}" ) \
$( siprefix "${array[1]}" ) \
"${array[2]}"
done | sed -e 's,~B, B,' -e 's,~#, #,'
}
# Get options
what=()
ANIMATE=1
for (( i=1; i<=$#; i++ )); do
[[ "${!i}" = "--help" ]] && helpexit
[[ "${!i}" = "-"* ]] && {
[[ "${!i}" =~ -.*a ]] && { ANIMATE=0; }
[[ "${!i}" =~ -.*h ]] && { helpexit; }
continue
}
what+=( "${!i}" )
done
[[ -z "${what[@]}" ]] && what="."
if [[ "$ANIMATE" -eq 1 ]]; then
trap 'trap - SIGTERM && kill -- -$$' EXIT SIGINT SIGTERM
animate &
fi
processfolders "${what[@]}"
if [[ "$ANIMATE" -eq 1 ]]; then
trap - EXIT SIGINT SIGTERM
kill %1
fi