Linux: How to delete all files whose file name is more than X characters in length

bashfile managementlinuxshell

I want to delete all files in the current directory and sub directories whose file name is more than a particular length.

Is there an easy way of doing this from bash?

Best Answer

You have already provided a find command that is safe for oddly named files:

find -regextype posix-egrep -type f -regex '.*[^/]{5}' -delete

This regex matches five trailing characters that do not contain a slash (i.e. the filename is longer than five chars).

The Bash loop you provided will generally work, but it probably does not scale with thousands of files and may break with special filenames.

An alternative that is similar in efficiency, but may provide more flexibility (replace rm by -n1 echo to print all files):

find -type f -print0 | grep -Ez '[^/]{5}$' | xargs -0 rm

The -print0, -z and -0 options ensure that each file name is terminated with a NUL byte. This ensures that special characters do not split filenames (newlines break the Bash command you provided). Although this grep command still fails with a name such as path/abc\ndef (where \n is a newline), it won't be split up into path/abc and def.

As you will rarely find files with \n in their name, I leave the implementation for that case as an exercise to the reader.