Skip to content
Advertisement

How to delete a subfolder with only a single file under the parent folder [closed]

I have a folder with 8000 subfolders, and want to delete those subfolders that only contain one file

Advertisement

Answer

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[@]}  $dirn"; 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[@]}  $dirn" exit; fi; done
1  ./subfolder_2
1  ./subfolder_5
Advertisement