Advertisements
Scenario
You have a complex folder structure and you want to remove all files and at the same time keep all folders intact.
We will present one method, using two variations of it that can achieve the above.
The method uses the GNU find command to find all files and delete them one by one.
Variation A
find . ! -type d -exec rm '{}' \;
This above command will search in the current directory and sub-directories for anything that is not a folder and then it will delete them.
find .
– Searches in this folder, since we did not define depth, it will search in all sub-folders as well! -type d
–type d
instructsfind
to match all Directories, by adding the!
in front of the instruction it negates the result and instructsfind
to match anything but the Directories-exec rm '{}' \;
– for every result, the command afterexec
is executed. The filename replaces'{}'
so that the results get deleted one by one.
Variation B
find . ! -type d -delete
In this example, we replaced -exec rm '{}' \;
with the simpler to remember directive of -delete
.