How to exclude a directory in find . command

后端 未结 30 1464
醉酒成梦
醉酒成梦 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:03

    -prune definitely works and is the best answer because it prevents descending into the dir that you want to exclude. -not -path which still searches the excluded dir, it just doesn't print the result, which could be an issue if the excluded dir is mounted network volume or you don't permissions.

    The tricky part is that find is very particular about the order of the arguments, so if you don't get them just right, your command may not work. The order of arguments is generally as such:

    find {path} {options} {action}
    

    {path}: Put all the path related arguments first, like . -path './dir1' -prune -o

    {options}: I have the most success when putting -name, -iname, etc as the last option in this group. E.g. -type f -iname '*.js'

    {action}: You'll want to add -print when using -prune

    Here's a working example:

    # setup test
    mkdir dir1 dir2 dir3
    touch dir1/file.txt; touch dir1/file.js
    touch dir2/file.txt; touch dir2/file.js
    touch dir3/file.txt; touch dir3/file.js
    
    # search for *.js, exclude dir1
    find . -path './dir1' -prune -o -type f -iname '*.js' -print
    
    # search for *.js, exclude dir1 and dir2
    find . \( -path './dir1' -o -path './dir2' \) -prune -o -type f -iname '*.js' -print
    

提交回复
热议问题