Reputation: 23
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
Upvotes: 1
Views: 942
Reputation: 312219
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
Upvotes: 2
Reputation: 23
I was able to achieve the required behavior by adding -mindepth 1 to the find command to exclude the parent directory.
Upvotes: 0