How to delete all the files and folders inside all the directories except some specific directory?

hi,

i have a requirement to delete all the files from all the directories except some specific directories like archive and log.
for example:
there are following directories such as
A B C D Archive E Log F
which contains some sub directories and files. The requirement is to delete all the files and subfolders except the contents of Archive and Log.

Why would you want to do this?
-- this appears to be a homework-type of problem, and not real-life.
What have you tried so far?

Not always. I had almost the same scenario where I had to create a script in my office for the another department guys.

Its not a homework question. I got a small task of clearing all the old files from all the directories except archive. Instead of going to each 200+ directories and deleting the files manually, thought of writing a script. Can someone please help.

find . -type d \( -name archive -o -name log \) -prune -o -type f -print

If this correctly prints the files to be deleted then replace -print by -delete or -exec rm -f {} +

1 Like

Thanks for the solution. Can you please explain it?

find . -type d
Searches for directories recursively starting from current folder.

\( -name archive -o -name log \) -prune
If directory is named archive or log then remove ( prune ) it from output of find command.

-o -type f -print
Otherwise print all files from the directories, except those pruned.

As MadeInGermany stated,

which will delete the files instead of printing them to the standard output.

3 Likes

-prune does not only suppress output, it really skips(prunes) these directories.
-o is logical OR, in a sequence has the meaning of "otherwise"
-a is logical AND, and can be omitted (is implicit), in a sequence has the meaning of "then"
\( -name archive -o -name log \) -prune
means: if name is "archive" OR if name is "log" then prune.
Perhaps the following "translation" make sense:

( if name is "archive" otherwise if name is "log" ) then if prune
otherwise if type is file then if print

The prune and print and delete and exec actions are always true.
The -exec is special: it is followed by a Unix command and arguments until there is a \; or a + ; a {} argument is replaced by the current file name.

2 Likes