How to delete only directories and leave files untouched
UnixDirectoryRmUnix Problem Overview
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
Unix Solutions
Solution 1 - Unix
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.
Solution 2 - Unix
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
Solution 3 - Unix
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.
Solution 4 - Unix
Simple way :-
rm -rf `ls -d */`
Solution 5 - Unix
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
Solution 6 - Unix
In one line:
rm -R `ls -1 -d */`
(backquotes)