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?
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: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):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 thisgrep command
still fails with a name such aspath/abc\ndef
(where\n
is a newline), it won't be split up intopath/abc
anddef
.As you will rarely find files with
\n
in their name, I leave the implementation for that case as an exercise to the reader.