1

On a linux host, given an absolute path, I want to delete all except a certain directory. To simplify things below is the directory structure and I want to delete all directories except test2

[root@hostname test]# pwd
/opt/data/test
root@hostname test]# ls -ltr
total 8
drwxr-xr-x 5 root root 4096 Dec  5 09:33 test1
drwxr-xr-x 2 root root 4096 Dec  5 09:44 test2
[root@hostname test]# 

I looked into How to exclude a directory in find . command and tried the prune switch like this

[root@hostname test]# find /opt/data/test -type d -path test2 -prune 
-o ! -name "test2" -print
/opt/data/test
/opt/data/test/test1
/opt/data/test/test1/ls.txt
/opt/data/test/test1/test13
/opt/data/test/test1/test13/temp.py
/opt/data/test/test1/test13/try.pl
/opt/data/test/test1/test11
/opt/data/test/test1/test11/ls.txt
/opt/data/test/test1/test11/temp.py
/opt/data/test/test1/test11/try.pl
/opt/data/test/test1/test12
/opt/data/test/test1/test12/ls.txt
/opt/data/test/test1/test12/temp.py
/opt/data/test/test1/test12/try.pl
/opt/data/test/test1/temp.py
/opt/data/test/test1/try.pl
/opt/data/test/test2/ls.txt
/opt/data/test/test2/temp.py
/opt/data/test/test2/try.pl
[root@hostname test]

now it lists all the folder including /opt/data/test and if I add the xargs rm -rf to this, it will delete the parent folder as well. I don't think I understood the concept -path and -name correctly, please help

mahradbt
  • 364
  • 1
  • 2
  • 12
Mukta
  • 23
  • 3

2 Answers2

1

Using a simple negation with -not may be easier than pruning:

$ find /opt/data/test -type d -not -name test2

EDIT:

There's no reason to recurse in to the subdirectories, since you're going to delete the top directories anyway, so you could add -maxdepth and avoid finding the directories inside test2:

$ find /opt/data/test -maxdepth 1 -type d -not -name test2
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • One problem with both the prune solution and this is that it also includes the folders within test2. As a result when I add pipe this with xargs rm -rf the contents within test2 are lost. How do I avoid this? [root@hostname test]# ls test1 test2 test3 test4 [root@hostname test]# cd [root@hostname-0 ~]# find /opt/data/test -type d -not -name test2 /opt/data/test /opt/data/test/test1 /opt/data/test/test1/test13 /opt/data/test/test1/test11 /opt/data/test/test1/test12 /opt/data/test/test2/test23 /opt/data/test/test2/test22 /opt/data/test/test2/test24 /opt/data/test/test2/test21 – Mukta Dec 05 '18 at 05:28
  • @Mukta You can use `-maxdepth`, see my edited answer. – Mureinik Dec 05 '18 at 05:33
  • -maxdepth helped – Mukta Dec 05 '18 at 10:47
0

I was able to achieve the required behavior by adding -mindepth 1 to the find command to exclude the parent directory.

Mukta
  • 23
  • 3