Hi im doing some cleaning up on my server and i want to know how would i get the total size of a folder of files that are 1mb and up and also 1mb and below. I got as far as:
ls -lh | grep 'M '
But i can't get the total size of everything.
Instead of parsing the output of ls
(which is considered really bad practice†), you could use find
and du
as so:
To find all files (-type f
) in current directory and subdirectories of size ≥1M (-size +1M
), and get the sum of their sizes:
find . -type f -size +1M -print0 | du -sch --files0-from=- | tail -1
Similar, but do not recurse in subdirectories (-maxdepth 1
):
find . -maxdepth 1 -type f -size +1M -print0 | du -sch --files0-from=- | tail -1
For files of size ≤1M:
find . -type f -size -1M -print0 | du -sch --files0-from=- | tail -1
find . -maxdepth 1 -type f -size -1M -print0 | du -sch --files0-from=- | tail -1
This works provided your version of du
supports the --files0-from
option.
If not, you could try this:
find . -type f -size +1M -exec du -sch {} + | tail -1
but if you have too many files, it won't work (you'll get a wrong answer)! In this case, you could try this instead:
find . -type f -size +1M -exec sh -c 'du -sch "$@" | tail -1' _ {} +
you'll then have several lines (hopefully not too many) and you'll have to do the math yourself.
With find
you have a complete control on which files you want to consider! it's filtering possibilities are mostly endless.
Cheers!
† You will get wrong answers with ls -1h | grep 'M '
in case you have files that contain the string "M "
. And the output of ls
is to be read by humans, not machines... machines have other much better means to obtain this kind of information.
This worked for me.
ls -lh | grep 'M' | awk '{ SUM += $5} END {print SUM}'
ls -l
output. (Which is the file size). Parsing ls output is considered bad form though and it will break if ls ever changes. Using find -ls does the same and is considered a better solution. And that can be combined with the -type f while using subdirectories.