Find linux exclude directory

How do I exclude a directory when using `find`?

I tried command above, but none of those using «-prune» works for me. Eventually I tried this out with command below:

find . \( -name "*" \) -prune -a ! -name "directory" 

For what I needed it worked like this, finding landscape.jpg in all server starting from root and excluding the search in /var directory:

find / -maxdepth 1 -type d | grep -v /var | xargs -I ‘<>‘ find ‘<>‘ -name landscape.jpg

find / -maxdepth 1 -type d lists all directories in /

grep -v /var excludes `/var’ from the list

xargs -I ‘<>‘ find ‘<>‘ -name landscape.jpg execute any command, like find with each directory/result from list

I consider myself a bash junkie, BUT . for the last 2 years have not find a single bash user friendly solution for this one. By «user-friendly» I mean just a single call away, which does not require me to remember complicated syntax + I can use the same find syntax as before , so the following solution works best for those ^^^

Copy paste this one in your shell and source the ~/.bash_aliases :

cat > ~/.bash_aliases # usage: source ~/.bash_aliases , instead of find type findd + rest of syntax findd() < dir=$1; shift ; find $dir -not -path "*/node_modules/*" -not -path "*/build/*" \ -not -path "*/.cache/*" -not -path "*/.git/*" -not -path "*/venv/*" $@ >EOF 

Of course in order to add or remove dirs to exclude you would have to edit this alias func with your dirs of choice .

Another example when using multiple patterns -o -name

To search in the root directory / for all *.tpl , *.tf files, excluding files which reside in /src/.terraform/ and /code/ .

$ find / -type f \( -name '*.tf' -o -name '*.tpl' \) \ -and \( -not -path '/src/.terraform/*' -and -not -path '/code/*' \) /src/debug.tf /src/nodegroup-infra.tpl /src/variables.tf.tpl 

I tested the above command with hyperfine; The test was conducted on a system with 3k directories and 12k files. I think it’s fair to say that it’s fast enough ~70ms

Benchmark #1: ./entrypoint.sh Time (mean ± σ): 69.2 ms ± 1.4 ms [User: 22.6 ms, System: 43.6 ms] Range (min … max): 66.4 ms … 72.2 ms 42 runs 

Sample Directory Structure

/code/ directory tree

bash-5.0# tree /code /code ├── debug.tf ├── entrypoint.sh ├── nodegroup-infra.tpl ├── tftemplate.sh └── variables.tf.tpl 0 directories, 5 files 

/src/ directory tree

bash-5.0# tree /src /src ├── Dockerfile ├── debug.tf ├── entrypoint.sh ├── nodegroup-infra.tpl ├── terraform.tfstate ├── terraform.tfstate.backup └── variables.tf.tpl 0 directories, 7 files 

/ root directory tree summary

$ tree / . 3382 directories, 12164 files 
find -type f -not -name .directoryname -printf "%f\n" 

If anyone looking to add find command inside Makefile, here is how we exclude directory

Below is the example to format all golang file excluding protobuf go files and all files under vendor directory:

find . ! -name '*.pb.go' -name '*.go' ! -path "*/vendor/*" -exec gofmt -s -w '<>' + 

This works because find TESTS the files for the pattern «*foo*«:

find ! -path "dir1" ! -path "dir2" -name "*foo*" 

but it does NOT work if you don’t use a pattern ( find does not TEST the file). So find makes no use of its former evaluated «true» & «false» bools. Example for not working use case with above notation:

find ! -path "dir1" ! -path "dir2" -type f 

There is no find TESTING! So if you need to find files without any pattern matching use the -prune. Also, by the use of prune find is always faster while it really skips that directories instead of matching it or better not matching it. So in that case use something like:

find dir -not \( -path "dir1" -prune \) -not \( -path "dir2" -prune \) -type f 
find dir -not \( -path "dir1" -o -path "dir2" -prune \) -type f 

I found the functions name in C sources files exclude *.o and exclude *.swp and exclude (not regular file) and exclude dir output with this command:

find . \( ! -path "./output/*" \) -a \( -type f \) -a \( ! -name '*.o' \) -a \( ! -name '*.swp' \) | xargs grep -n soc_attach 
 find . -name '*.js' -not -path '*exclude/this/dir*' 

Better use the exec action than the for loop:

find . -path "./dirtoexclude" -prune \ -o -exec java -jar config/yuicompressor-2.4.2.jar --type js '<>' -o '<>' \; 

The exec . ‘<>‘ . ‘<>‘ \; will be executed once for every matching file, replacing the braces ‘<>‘ with the current file name.

Читайте также:  Последнее обновление линукс минт

Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation * .

Notes

* From the EXAMPLES section of the find (GNU findutils) 4.4.2 man page

Very old question, but still with room for improvements. I found it by chance trying to solve a similar problem, and none of the answers were satisfactory.

I use the exec action often and find it very useful. I typically add quotes between the <> in case there are spaces in the file paths which gives «<>» .

@lkuty I was about to edit my post to reflect your comment, but after a quick test (without quoting, <> does work for files with whitespaces in their names) and a look into the man pages, it seems that quoting is only necessary to avoid them to be misinterpreted as shell script punctuation. In this case, you would use single quoting: ‘<>‘

If search directories has pattern (in my case most of the times); you can simply do it like below:

In above example; it searches in all the sub-directories starting with «n».

I have found the suggestions on this page and a lot of other pages just do not work on my Mac OS X system. However, I have found a variation which does work for me.

The big idea is to search the Macintosh HD but avoid traversing all the external volumes, which are mostly Time Machine backups, image backups, mounted shares, and archives, but without having to unmount them all, which is often impractical.

Here is my working script, which I have named «findit».

#!/usr/bin/env bash # inspired by http://stackoverflow.com/questions/4210042/exclude-directory-from-find-command Danile C. Sobral # using special syntax to avoid traversing. # However, logic is refactored because the Sobral version still traverses # everything on my system echo ============================ echo find - from cwd, omitting external volumes date echo Enter sudo password if requested sudo find . -not \( \ -path ./Volumes/Archive -prune -o \ -path ./Volumes/Boot\ OS\ X -prune -o \ -path ./Volumes/C \ -path ./Volumes/Data -prune -o \ -path ./Volumes/jas -prune -o \ -path ./Volumes/Recovery\ HD -prune -o \ -path ./Volumes/Time\ Machine\ Backups -prune -o \ -path ./Volumes/SuperDuper\ Image -prune -o \ -path ./Volumes/userland -prune \ \) -name "$1" -print date echo ============================ iMac2:~ jas$ 

The various paths have to do with external archive volumes, Time Machine, Virtual Machines, other mounted servers, and so on. Some of the volume names have spaces in them.

Читайте также:  Адаптер блютуз для линукса

A good test run is «findit index.php», because that file occurs in many places on my system. With this script, it takes about 10 minutes to search the main hard drive. Without those exclusions, it takes many hours.

Not sure if this would cover all edge cases, but following would be pretty straight forward and simple to try:

ls -1|grep -v -e ddl -e docs| xargs rm -rf

This should remove all files/directories from the current directory excpet ‘ddls’ and ‘docs’.

for file in $(find . -name '*.js') do java -jar config/yuicompressor-2.4.2.jar --type js $file -o $file done 

. and since you don’t define which subdirectory you want to exclude, you could use:

for file in $(find *.js -maxdepth 0 -name '*.js') do java -jar config/yuicompressor-2.4.2.jar --type js $file -o $file done 

This syntax will exclude all subdirectories.

Take a look at the example below: under my tmp directory I have an huge «archive» subdirectory which contains 17000-4640=12360 files. And this directory is located on a slow NFS. While the 1st syntax scans the «archive» subdirectory and performs poorly, the 2nd syntax only scans the «*pdf» files contained in my current dir and performs. not that bad.

[tmp]$ time (find . -name "*pdf" | wc -l) 17000 real 0m40.479s user 0m0.423s sys 0m5.606s [tmp]$ time (find *pdf -maxdepth 0 -name "*pdf" | wc -l) 4640 real 0m7.778s user 0m0.113s sys 0m1.136s 

That 2nd syntax is quite interesting: in the following example I want to check if file or60runm50958.pdf exists and is more than 20 minutes old. See for yourself how the 2nd syntax is more efficient. This is because it avoids scanning the archive subdirectory.

[tmp]$ time find . -name or60runm50958.pdf -mmin +20 ./or60runm50958.pdf real 0m51.145s user 0m0.529s sys 0m6.243s [tmp]$ time find or60runm50958.pdf -maxdepth 0 -name or60runm50958.pdf -mmin +20 or60runm50958.pdf real 0m0.004s user 0m0.000s sys 0m0.002s 

i wanted to know the number of directories, files an MB of just the current directory — and that code does exactly what i want 🙂

- . 2791037 Jun 2 2011 foo.jpg - . 1284734651 Mär 10 16:16 foo.tar.gz - . 0 Mär 10 15:28 foo.txt d . 4096 Mär 3 17:12 HE d . 4096 Mär 3 17:21 KU d . 4096 Mär 3 17:17 LE d . 0 Mär 3 17:14 NO d . 0 Mär 3 17:15 SE d . 0 Mär 3 17:13 SP d . 0 Mär 3 17:14 TE d . 0 Mär 3 19:20 UN 
format="%s%'12d\n" find . -type d -not -path "./*/*" | wc -l | awk -v fmt=$format '' find . -type f -not -path "./*/*" | wc -l | awk -v fmt=$format '' du . -hmS --max-depth=0 | awk -v fmt=$format ' is necessary for awk to format the numbers.

the result

Anzahl Ordner = 8 Anzahl Dateien = 3 Groesse (MB) = 1.228 

Please translate non-English code/output citations. Note that you can switch the typical Linux tool output from German back to English by running the tools in a shell with LC_ALL=C .

#find command in linux def : find command used to locate /search files in unix /linux system , find search for files in a directory hierarchy 
1)exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir 2)-options -H =do not follow symoblic links while except while procesing . -L = follow symbolic links -P =never follow symbolic links -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) -Delete Delete files; true if removal succeeded. If the removal failed, an error message is issued. If -delete #fails, find's exit status will be nonzero (when it eventually exits). find /home/mohan/a -mindepth 3 -maxdepth 3 -type f -name "*.txt" |xargs rm -rf find -type d -name find -type f -Name find /path/ -type f -iname (i is case insenstive) #find directores a/b/c and only delete c directory inside have "*.txt " find /home/mohan/a -mindepth 3 -maxdepth 3 -type f -name "*.txt" |xargs rm -rf find /home/mohan/a -mindepth 3 -maxdepath 3 -type f -name "*.txt" -delete #delete particular directory have empty file and only we can delete empty files find /home/mohan -type f -name "*.txt" -empty -DELETE #find multiple files and also find empty files find /home/mohan -type f \( -name "*.sh" -o -name "*.txt" \) -empty #delete empty files two or more Files find /home/mohan -type f \( -nmae "*.sh" -o -name "*.txt" \) -empty -delete #How to append contents of multiple files into one file find . -type f -name '*.txt' -exec cat <> + >> output.file #last modified files finding using less than 1 min (-n) ls -lrth|find . -type f -mmin -1 #last modified files more than 1 min (+n) ls -lrth|find . -type f -mmin +1 #last modified files exactly one mins find . -type f -mmin 1 last modifiedfiles exactly in one day by using command (-mtime) find . -type f -mtime 10 #last modified more than 10 days find . -type f -mtime +10 #last modified less than 10 days find . -type f -mtime -10 #How to Find Modified Files and Folders Starting from a Given Date to the Latest Date find . -type f -newermt "17-11-2020" #How to Find a List of “sh” Extension Files Accessed in the Last 30 Days--- -matdimtype ls -lrt|find . -type f -iname ".sh" -atime -30 #How to Find a List of Files Created Today, -1 means less than min, ls -lrt | find . -type f -ctime -1 -ls 

Источник

Оцените статью
Adblock
detector