Delete all files and keep the directory structure


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 dtype d instructs find to match all Directories, by adding the ! in front of the instruction it negates the result and instructs find to match anything but the Directories
  • -exec rm '{}' \; – for every result, the command after exec 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.

This post is also available in: Greek

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.