Using "du" for Total File Size of Certain File Types

1.3k views Asked by At

I have been using the du command to get the size of a directory:

du /tmp/dir1

This produced the total size of the files:

7   /tmp/dir1

Which I then parse and use the details.

This folder is full of .txt and txr files. I am only interested in the total size of the *.txt files.

Is there a way I can odify the du command to produce a single line output of the size of just the *.txt files?

5

There are 5 answers

4
Rubens On BEST ANSWER

Pass a list of files to the du command. For example:

du -s /tmp/dir1/*.txt

A possible solution to getting only the total size is to get the last line of du's output, as in:

du -c /tmp/dir1/*.txt | tail -1
3
Martin Tournoij On

du doesn't have an easy way to filter the output; but we can use find with stat to get the filesize, and then awk to sum it up:

$ find /tmp/dir1 -name '*.txt' -exec stat -c %s {} + | awk '{s+=$1} END {print s}' 

Note this will only work on Linux/GNU systems, due to incompatible stat arguments.

1
Dummy00001 On

Use the --exclude option:

du --exclude '*.krt' /tmp/dir1
0
chimbu On

You can also check the size of a directories and files by means of the below command.

Navigate to path(/tmp/dir1) du -sh * or du -sh /tmp/dir1

  • s represents Sum of directories.
  • h represents human readable format.
0
Raju On

Here are the possible options:

  • If you want the size of each '.txt' file in the same dir (/tmp/dir1). And at the end, it will also print the total size of all '.txt' files

du -csh *.txt

  • Recursively find the size of each '.txt' file in the given dirs/sub-dirs of any depth and print the total size of all those files at the end

find -name "*.txt" -exec du -csh '{}' +

Note: you can replace .txt with any other file types