Find but do not descend into directories containing the searched files

强颜欢笑 提交于 2020-01-14 10:42:47

问题


I have several projects configured by a pom.xml or similar.

I would like to use the linux file command to locate these projects e.g. by find -name pom.xml. This however takes some time because of the deep paths. I would like to use find -prune to stop searching in subdirectories when I already find the file, but prune only stops on matched directories not on matched files.

Is there a way to get find to stop descending when the directory aleady contains a searched file?

For clarification; this is what I do without find:

pfind() {
    parent=$1 && shift

    for file in "$@" ; do
        path=$parent/$file
        if [ -e "$path" ] ; then
            echo "$path"
            exit 0
        fi
    done

    for dir in $(echo $parent/*) ; do
       if [ -d "$dir" ] ; then
           pfind "$dir" "$@"
       fi
    done
}

But I'd rather use a simple way with find so it is better understandable/extendable for others


回答1:


find . -name pom.xml -print -quit

If you want to speed up the search, you can also work with locate, which queries a database instead of scanning the file system.

You can update the database using by running updatedb




回答2:


One line python:

python -c 'import os; print "\n".join(p for p, d, f in os.walk(os.sys.argv[1], topdown=True) if os.sys.argv[2] in f and list(d.remove(i) for i in list(d)))' $PWD pom.xml

os.walk idea from https://stackoverflow.com/a/37267686/1888983



来源:https://stackoverflow.com/questions/28107496/find-but-do-not-descend-into-directories-containing-the-searched-files

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!