I have a folder with 8000 subfolders, and want to delete those subfolders that only contain one file
Asked
Active
Viewed 123 times
1 Answers
1
Considering all of the subfolders
are in the same folder with no "sub-sub" depth, find
command prints subfolders with this one-liner and bash
handles the rest:
Sample folder and files:
$ find .
.
./subfolder_1
./subfolder_1/file1
./subfolder_1/file2
./subfolder_1/file3
./subfolder_2
./subfolder_2/file4
./subfolder_3
./subfolder_3/file5
./subfolder_3/file6
./subfolder_4
./subfolder_5
./subfolder_5/file7
One liner to remove subfolders containing only one file:
$ find . -not -empty -type d -print0 | while read -d '' -r dir; do files=("$dir"/*); if((${#files[@]} == "1")); then rm -r $dir exit; fi; done
List of what is remained after removing
$ find .
.
./subfolder_1
./subfolder_1/file1
./subfolder_1/file2
./subfolder_1/file3
./subfolder_3
./subfolder_3/file5
./subfolder_3/file6
./subfolder_4
Extra
List of subfolders with the number of files included:
$ find . -not -empty -type d -print0 | while read -d '' -r dir; do files=("$dir"/*); printf "${#files[@]} $dir\n"; done
6 .
3 ./subfolder_1
1 ./subfolder_2
2 ./subfolder_3
1 ./subfolder_5
List of subfolders containing only one file:
$ find . -not -empty -type d -print0 | while read -d '' -r dir; do files=("$dir"/*); if((${#files[@]} == "1")); then printf "${#files[@]} $dir\n" exit; fi; done
1 ./subfolder_2
1 ./subfolder_5

Ahmet Said Akbulut
- 426
- 4
- 17
-
1Thank you very much! ! ! This is exactly what I want as a newbie to bash shell script – 赠人玫瑰手留余香 Jul 07 '21 at 02:32
-
I am glad you benefit it. This is a modification from here https://stackoverflow.com/a/15221702/14320738 you can examine this post for more information. – Ahmet Said Akbulut Jul 07 '21 at 06:12