Skip to main content

Delete all files & directories in a folder except one file [Resolved]

I want to delete all files & directories in a folder say 'A'. But except one file in that folder say .keep. I have tried the following command.

find A ! -name '.keep' -type f -exec rm -f {} +

But above command also deletes folder A. I do not want that. There are several answers related to this. But they all mentions going into that directory. I want to mention that directory in the command without cd-eing into the directory.


Question Credit: Dushyant Joshi
Question Reference
Asked July 13, 2019
Tags: linux, command
Posted Under: Network
33 views
2 Answers

find A ! -path A/.keep -a ! -path A -delete


credit: 84104
Answered July 13, 2019

In short, you find the files you want to keep, and after a -o (short for "or") which will get all the "other" non-matching files, you can do whatever you need.

Another useful argument is -mindepth 1, which can let you easily skip the top level (level 0).

Here is an example, initiate the tree like this:

$ mkdir a a/b; touch a/{c,d,e,keep1} a/b/{f,g,h,keep2}

$ find a/ -exec ls -gGd {} +
drwxr-xr-x 1 18 Jul 12 14:31 a/
drwxr-xr-x 1 16 Jul 12 14:31 a/b
-rw-r--r-- 1  0 Jul 12 14:31 a/b/f
-rw-r--r-- 1  0 Jul 12 14:31 a/b/g
-rw-r--r-- 1  0 Jul 12 14:31 a/b/h
-rw-r--r-- 1  0 Jul 12 14:31 a/b/keep2
-rw-r--r-- 1  0 Jul 12 14:31 a/c
-rw-r--r-- 1  0 Jul 12 14:31 a/d
-rw-r--r-- 1  0 Jul 12 14:31 a/e
-rw-r--r-- 1  0 Jul 12 14:31 a/keep1

The command you'd need to wipe all files except the "keep" ones can be:

$ find a/ -mindepth 1 -name keep1 -o -name keep2 -o \( -not -type d -exec ls -gGd {} + \)
-rw-r--r-- 1 0 Jul 12 14:31 a/b/f
-rw-r--r-- 1 0 Jul 12 14:31 a/b/g
-rw-r--r-- 1 0 Jul 12 14:31 a/b/h
-rw-r--r-- 1 0 Jul 12 14:31 a/c
-rw-r--r-- 1 0 Jul 12 14:31 a/d
-rw-r--r-- 1 0 Jul 12 14:31 a/e

As you can see, keep1 and keep2 are not in the list of arguments passed to the ls command. Feel free to replace ls -gGd with rm -vf :)

You can adjust the arguments in the parentheses if you have more requirements.


credit: chutz
Answered July 13, 2019
Your Answer
D:\Adnan\Candoerz\CandoProject\vQA