Posts Tagged ‘bash’

1 Comment

Find the total size of certain files within a directory tree before deleting them

Friday, January 13th, 2023

Normally I use find, as it is installed by default on any Linux computer or server or terminal I worked with, but lately on my desktop I start using `fdfind` more and more.

Why? Its faster and easier to work with than find.

I really like the user-friendly syntax of `fd` AKA `fd-find` or `fdfind` compared to the classic `find` command.

In Ubuntu the program is installed with `sudo apt install fd-find` and executed as `fdfind`

`fd` uses a regex as the standard search pattern.

Time for some examples.

To find all files in a directory tree that have jpg in their name

Very intuitive and concise.

fdfind jpg

To find all jpg files (extension jpg) in a directory tree

Think I need all files with [e]xtension jpg, the command is again very intuitive:

fdfind -e jpg

To delete all jpg files in a directory tree

Think I need all files with [e]xtension jpg then e[x]ecute a command to delete them [rm], the command is very intuitive:

As the normal delete command in bash is `rm`

fdfind -e jpg -x rm

That’s all.

Another interesting thing to know, what disk-space I’m gonna win by deleting all jpg files.

Find the total size of jpg files within a directory tree (wrongly)

Think: I need all files, and then calculate the filespace of all files.

The normal command of getting a total size of several files is use `du -ch *.jpg` This will list of files and Count a total on the last line. To get just the last line. pipe it to tail, to gets just the last line.

du -ch *.jpg |  tail -1

But du doesn’t work recursive in subdirectory. You can use a trick with globstar, but much easier is it to combine with fd, so you would come to something like this.

fdfind -e jpg -x du -ch | tail -1

But that doesn’t work right, it seems to computes totals for every file, and just show to size of the last result.

Find the total size of jpg files within a directory tree (correctly)

We need the `-X` option here the `execute-batch` command, that runs the command only once on all search results as arguments

fdfind -e jpg -X du -ch | tail -1

Find correctly find the total size of jpg files in a directory and the first level of subdirectories

And with `fdfind` command it’s easy to control Depth, just add a -d option. This will only search in the main and the first subdirectory level.

fdfind -d 2 -e jpg -X du -ch | tail -1

And now you ask yourself. Can I find the size of all jpg files in the third level of subdirectories.

Of course! And easier than you think

Find the total size of jpg files in the third level of subdirectories depth

fdfind --min-depth 4 --max-depth 4 -e jpg -X du -ch | tail -1

See more:

https://github.com/sharkdp/fd