Python for Network Engineers

Find the Total Size of All Files With Certain Extension with one Line

by: George El., January 2019, Reading time: 2 minutes

find all files with a certain extension in current directory and add the file sizes to calculate total file size in Mbytes

find . -iname "*.txt" | xargs ls -l | awk '{print $5 }' | paste -sd+ | bc |  awk '{print $1/1024/1024 }'

the above example finds all files ending in txt, starting from the current directory. If you want to find the size of your mp3 files, you would do “.mp3”. if you want to search from root directory to find all files you will use / instead of “.” that is find / -iname “.mp3” | xargs ls -l | awk ‘{print $5 }’ | paste -sd+ | bc | awk ‘{print $1/1024/1024 }’

find just finds all names ending in *.txt, i ignore case.

$ find . -iname "*.txt" 
./file1.txt
./file2.txt
./file3.txt

then we pass all files to xargs ls -l

$ find . -iname "*.txt" | xargs ls -l 
-rw-rw-r-- 1 geo geo 1048576 Jan 17 09:06 ./file1.txt
-rw-rw-r-- 1 geo geo 2097152 Jan 17 09:06 ./file2.txt
-rw-rw-r-- 1 geo geo 3145728 Jan 17 09:07 ./file3.txt

now all I have is to isolate the 5th column that contains the byte size, this is easy with awk

$ find . -iname "*.txt" | xargs ls -l | awk '{print $5 }'
1048576
2097152
3145728

then I have to put all these lines into a single line and add as a delimiter the + symbol. this is accomplished with paste command

$ find . -iname "*.txt" | xargs ls -l | awk '{print $5 }' | paste -sd+
1048576+2097152+3145728

finally adding the numbers using bc

$ find . -iname "*.txt" | xargs ls -l | awk '{print $5 }' | paste -sd+ | bc
6291456

lets convert it to Kbytes by dividing by 1024

$ find . -iname "*.txt" | xargs ls -l | awk '{print $5 }' | paste -sd+ | bc | awk '{print $1/1024 }'
6144

lets convert it to Mbytes by dividing twice by 1024

$ find . -iname "*.txt" | xargs ls -l | awk '{print $5 }' | paste -sd+ | bc | awk '{print $1/1024/1024 }'
6
comments powered by Disqus