ajnair95
ajnair95

Reputation: 59

How to find the count of and total sizes of multiple files in directory?

I have a directory, inside it multiple directories which contains many type of files.

I want to find *.jpg files then to get the count and total size of all individual one.

I know I have to use find wc -l and du -ch but I don't know how to combine them in a single script or in a single command.

find . -type f name "*.jpg" -exec - not sure how to connect all the three

Upvotes: 3

Views: 3249

Answers (1)

swingbit
swingbit

Reputation: 2745

Supposing your starting folder is ., this will give you all files and the total size:

find . -type f -name '*.jpg' -exec du -ch {} +

The + at the end executes du -ch on all files at once - rather than per file, allowing you the get the frand total. If you want to know only the total, add | tail -n 1 at the end.

Fair warning: this in fact executes

du -ch file1 file2 file3 ... 

Which may break for very many files. To check how many:

$ getconf ARG_MAX
2097152

That's what is configured on my system.

This doesn't give you the number of files though. You'll need to catch the output of find and use it twice.

The last line is the total, so we'll use all but the last line to get the number of files, and the last one for the total:

OUT=$(find . -type f -name '*.jpg' -exec du -ch {} +)
N=$(echo "$OUT" | head -n -1 | wc -l)
SIZE=$(echo "$OUT" | tail -n 1)
echo "Number of files: $N"
echo $SIZE

Which for me gives:

Number of files: 143
584K    total

Upvotes: 6

Related Questions