Reputation: 1195
I have hundreds of directories and files in one directory.
What is the best way deleting only directories (no matter if the directories have anything in it or not, just delete them all)
Currently I use ls -1 -d */
, and record them in a file, and do sed
, and then run it. It rather long way. I'm looking for better way deleting only directories
Upvotes: 92
Views: 70586
Reputation: 31
I have done this, by adding a way to preserve one folder. I execute the command in a subfolder for removing folders in the parent one. It doesn't work for directory names with spaces:
parent folder => CleanTheSystem
subfolder_to_be_preserved => Linux
file in the subfolder_to_be_preserved => OK_Mackay.txt
subfolder_to_delete => Windows
too_many_files => ***
rm -r $(ls -1 -d ../*/ | grep -v Linux);
And this works for folder names with spaces:
find ../. -type d -name "* *" -execdir bash -c 'mv "$1" "${1// /_}"' _ {} \; 2>/dev/null;rm -r $(ls -1 -d ../*/ | grep -v Linux);
Warning!: Be careful. If you misspell Linux, everything will be erased.
Upvotes: 0
Reputation: 564
find command only (it support file deletion)\
find /path -depth -type d -delete
-type d looks only for directories, then -depth makes sure to put child directories before the parent. -delete removing filtered files/folders
Upvotes: 0
Reputation: 6646
To delete all directories and subdirectories and leave only files in the working directory, I have found this concise command works for me:
rm -r */
It makes use of bash wildcard */
where star followed by slash will match only directories and subdirectories.
Upvotes: 268
Reputation: 1955
find . -maxdepth 1 -mindepth 1 -type d
then
find . -maxdepth 1 -mindepth 1 -type d -exec rm -rf '{}' \;
To add an explanation:
find
starts in the current directory due to .
and stays within the current directory only with -maxdepth
and -mindepth
both set to 1
. -type d
tells find
to only match on things that are directories.
find
also has an -exec
flag that can pass its results to another function, in this case rm
. the '{}' \;
is the way these results are passed. See this answer for a more complete explanation of what {}
and \;
do
Upvotes: 41
Reputation: 70497
First, run:
find /path -d -type d
to make sure the output looks sane, then:
find /path -d -type d -exec rm -rf '{}' \;
-type d
looks only for directories, then -d
makes sure to put child directories before the parent.
Upvotes: 14