Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to exclude all subdirectories of a given directory in the search path of the find command in unix

Tags:

linux

bash

unix

I need to backup all the directory hierarchy of our servers, thus I need to list all the sub directories of some of the directories in the server.

The problem is that one of those sub directories contains tens of thousands of sub directories (file with only the names of the sub directories could take couple of hundreds megabytes and the respective find command takes very long).

For example, if I have a directory A and one sub directory A/a that contains tens of thousands of sub directories, I want to use the find command to list all the sub directories of A excluding all the sub directories of A/a but not excluding A/a itself.

I tried many variations of -prune using the answers in this question to no avail.

Is there a way to use the find command in UNIX to do this?

UPDATE:

the answer by @devnull worked very well, but now i have another problem, so i will refine my question a little:

i used the following command:

 find /var/www -type d \( ! -wholename "/var/www/web-release-data/*"  ! -wholename "/var/www/web-development-data/*" \)

the new problem that arises is that find for some reason is still traversing the whole directory tree of "/var/www/web-release-data/" and "/var/www/web-development-data/", thus it's very slow, and I fear it could take hours.

Is there any way make find completely exclude those directories and not traverse their respective directory hierarchies?

like image 989
DontCareBear Avatar asked Sep 10 '13 15:09

DontCareBear


People also ask

How do I exclude a subdirectory in find?

We can exclude directories by using the help of “path“, “prune“, “o” and “print” switches with find command. The directory “bit” will be excluded from the find search!

How do I exclude a directory in find command?

To exclude multiple directories, OR them between parentheses. And, to exclude directories with a specific name at any level, use the -name primary instead of -path .

Which command is used to search all directory and subdirectories?

The find command will begin looking in the starting directory you specify and proceed to search through all accessible subdirectories.

Which rm command remove directory with all its subdirectories?

To remove a directory and all its contents, including any subdirectories and files, use the rm command with the recursive option, -r .


1 Answers

The following should work for you:

find A -type d \( ! -wholename "A/a/*" \)

This would list all subdirectories of A including A/a but excluding subdirectories of A/a.

Example:

$ mkdir -p A/{a..c}/{1..4}
$ find A -type d \( ! -wholename "A/a/*" \)
A
A/c
A/c/4
A/c/2
A/c/3
A/c/1
A/a
A/b
A/b/4
A/b/2
A/b/3
A/b/1
like image 139
devnull Avatar answered Oct 31 '22 09:10

devnull