-2

i want to use find and delete everything with the exception of one folder if found. e.g.

[oracle@SJOAM test]$ ls -l
total 4
-rw-r--r--. 1 oracle oinstall    0 Sep  2 02:05 a
-rw-r--r--. 1 oracle oinstall    0 Sep  2 02:05 b
-rw-r--r--. 1 oracle oinstall    0 Sep  2 02:05 c
-rw-r--r--. 1 oracle oinstall    0 Sep  2 02:05 d
-rw-r--r--. 1 oracle oinstall    0 Sep  2 02:05 e
-rw-r--r--. 1 oracle oinstall    0 Sep  2 02:05 f
-rw-r--r--. 1 oracle oinstall    0 Sep  2 02:05 g
drwxr-xr-x. 2 oracle oinstall 4096 Aug  7 07:25 test2

I wanted to delete everything except test2.

So i started with

[oracle@SJOAM test]$ find test2 -prune -o -print
[oracle@SJOAM test]$ 

Return nothing.

q1) why isn't the above command without -name showing the rest of the files ? but with a "-name" shown below showing the rest of the files ?

[oracle@SJOAM test]$ find -name test2 -prune -o -print
.
./e
./a
./b
./d
./f
./g
./c

With -name , i can see the rest of the files. But i can still see the "." current folder.

[oracle@SJOAM test]$ find -name test2 -prune -o -exec rm -r '{}' \;
rm: cannot remove directory: `.'
[oracle@SJOAM test]$ ls -l
total 4
drwxr-xr-x. 2 oracle oinstall 4096 Aug  7 07:25 test2

Well, all files are removed. But I kinda feel it is not the correct way -- it attempt to delete "."

q2) How to i prevent the delete of "." ?

Also,

[oracle@SJOAM test]$ find test2
test2
test2/a9
test2/a8
test2/a7
test2/a10
[oracle@SJOAM test]$ find -name test2
./test2
[oracle@SJOAM test]$ 

q3) Why -name is showing ./test , but without -name, it is not showing the "./" ?

  • rm *. This won't delete test2 because it's a directory. – Cyrus Sep 1 '15 at 18:55
  • what if i wanted to delete directory also...other then test2 – Noob Sep 2 '15 at 4:04
0

This works fine

find . ! -name test2 ! -name . -exec rm -r '{}' \;

By adding ! -name ..., we tell find to skip . and test2 objects.

Answering to your first question, from man find:

find [-H] [-L] [-P] [-D debugopts] [-Olevel] [path...] [expression]

As you see, if you don't provide first options before the [path...], find treats the first argument as a path to search in, so when you do find test2 -prune -o -print, it lists all files in the test2 folder but reverses the output due to the OR statement ordered by -prune -o. This answer is related to your third question too.

  • what does ! means ? – Noob Sep 2 '15 at 4:04
  • ! is a logical not operator. In this case it tells find to not match filename, when the default expression of -name is match filename – Tim Sep 2 '15 at 11:42

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.