3

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.

1

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

  • It would be more helpful to the questioner to the person asking the question to explain the different parts of the command. – Nasir Riley Jul 12 at 5:15
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.