How to exclude a directory in find . command

后端 未结 30 1358
醉酒成梦
醉酒成梦 2020-11-22 03:36

I\'m trying to run a find command for all JavaScript files, but how do I exclude a specific directory?

Here is the find code we\'re using.<

相关标签:
30条回答
  • 2020-11-22 04:13

    To exclude multiple directories:

    find . -name '*.js' -not \( -path "./dir1" -o -path "./dir2/*" \)
    

    To add directories, add -o -path "./dirname/*":

    find . -name '*.js' -not \( -path "./dir1" -o -path "./dir2/*" -o -path "./dir3/*"\)
    

    But maybe you should use a regular expression, if there are many directories to exclude.

    0 讨论(0)
  • 2020-11-22 04:14

    One option would be to exclude all results that contain the directory name with grep. For example:

    find . -name '*.js' | grep -v excludeddir
    
    0 讨论(0)
  • 2020-11-22 04:14

    This is suitable for me on a Mac:

    find . -name *.php -or -path "./vendor" -prune -or -path "./app/cache" -prune
    

    It will exclude vendor and app/cache dir for search name which suffixed with php.

    0 讨论(0)
  • 2020-11-22 04:15

    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

    0 讨论(0)
  • 2020-11-22 04:18

    I prefer the -not notation ... it's more readable:

    find . -name '*.js' -and -not -path directory
    
    0 讨论(0)
  • 2020-11-22 04:18

    You can also use regular expressions to include / exclude some files /dirs your search using something like this:

    find . -regextype posix-egrep -regex ".*\.(js|vue|s?css|php|html|json)$" -and -not -regex ".*/(node_modules|vendor)/.*" 
    

    This will only give you all js, vue, css, etc files but excluding all files in the node_modules and vendor folders.

    0 讨论(0)
提交回复
热议问题