Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate size of files in shell

Tags:

linux

shell

I'm trying to calculate the total size in bytes of all files (in a directory tree) matching a filename pattern just using the shell. This is what I have so far:

find -name *.undo -exec stat -c%s {} \; | awk '{total += $1} END {print total}'

Is there an easier way to do this? I feel like there should be a simple du or find switch that does this for me but I can't find one.

To be clear I want to total files matching a pattern anywhere under a directory tree which means

du -bs *.undo

won't work because it only matches the files in the current directory.

like image 703
yothenberg Avatar asked Mar 01 '09 00:03

yothenberg


People also ask

How do I find the size of a file in Shell?

Getting file size using find command find "/etc/passwd" -printf "%s" find "/etc/passwd" -printf "%s\n" fileName="/etc/hosts" mysize=$(find "$fileName" -printf "%s") printf "File %s size = %d\n" $fileName $mysize echo "${fileName} size is ${mysize} bytes."

How do I see the size of a file in bash?

Another method we can use to grab the size of a file in a bash script is the wc command. The wc command returns the number of words, size, and the size of a file in bytes.

How do I check a files size?

Click the file or folder. Press Command + I on your keyboard. A window opens and shows the size of the file or folder.

How does Linux calculate file size?

Find File size with Du command in Linux What we need is to open the terminal and type du -sh file name in the prompt. The file size will be listed on the first column. The size will be displayed in Human Readable Format. This means we can see file sizes in Bytes, Kilobytes, Megabytes, Gigabytes, etc.


2 Answers

Try:

find . -name "*.undo" -ls | awk '{total += $7} END {print total}' 

On my system the size of the file is the seventh field in the find -ls output. If your find … -ls output is different, adjust.

In this version, using the existing directory information (file size) and the built-in ls feature of find should be efficient, avoiding process creations or file i/o.

like image 166
tpgould Avatar answered Sep 25 '22 13:09

tpgould


With zsh, you can use extended globbing to do:

du -c **/*.undo

like image 30
Chris AtLee Avatar answered Sep 24 '22 13:09

Chris AtLee