gpt4 book ai didi

linux - 如何使用 "find"命令限制对目录的搜索?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:35:24 26 4
gpt4 key购买 nike

我正在尝试制作一个 Bash 脚本,该脚本将创建指向具有“目标”子目录的目录的符号链接(symbolic link)。我使用“查找”命令搜索“目标”目录并将文件路径放入数组。

array_of_dirs=( $(find -type d -name "target") )

数组被循环遍历,符号链接(symbolic link)被建立到目录。我的问题是目录结构的深度未知,子目录可以有多个“目标”目录。

目录结构可以是:

    .
├── blaah
│   ├── jee1
│   │   └── omg1
│   │   └── bar1
│   │   └── target <--- When this is found, no need to continue into subdirectories
│   │   └── wtf1
│   │   └── target
│   ├── jee2
│   │   └── target
│   ├── jee3
│   └── jee4
└── blaah2
├── jou1
│   └── target
├── jou2
└── jou3
└── target <--- When this is found, no need to continue into subdirectories
├── foo1
│   └── target
├── foo2
│   └── target
└── foo3
└── target

目前已找到这些路径并且创建了不需要的符号链接(symbolic link)。

    ./blaah/jee1/omg1/bar1
./blaah/jee1/omg1/bar1/target/wtf1 <--- Unwanted
./blaah/jee2
./blaah2/jou1
./blaah2/jou3
./blaah2/jou3/target/foo1 <--- Unwanted
./blaah2/jou3/target/foo2 <--- Unwanted
./blaah2/jou3/target/foo3 <--- Unwanted

当找到“目标”时,我如何限制搜索不会继续深入子目录?

最佳答案

最短的解决方案优先,即使最后找到了(伊士曼本人在评论中建议)。

array_of_dirs=($(find -type d -name "foo" -prune))

使用 -path 选项,您可以排除包含整个标记“/target/”的路径。与仅评估文件名本身的 -name 相比,路径需要通配以捕获 foo/target 和 target/bar。当然,它需要否定 - 而不是 -path "/target/"。

array_of_dirs=($(find -type d -not -path "*/target/*" -name "target"))

在我的系统和 foo 而不是目标上进行测试:

find -type d -name "foo" 
./tmp/bar/bar/foo
./tmp/bar/foo
./tmp/test/bar/foo
./tmp/foo
./tmp/foo/foo
./tmp/foo/foo/foo

find -type d -not -path "*/foo/*" -name "foo"
./tmp/bar/bar/foo
./tmp/bar/foo
./tmp/test/bar/foo
./tmp/foo

选项 -path ... -prune 似乎具有相同的效果。详细区别请仔细阅读说明书。一个简短的测试显示使用修剪可节省 10% 的时间,但这可能是缓存效应或随机影响。

(不必要冗长的中间解决方案:)

find -type d -name "foo"-path " /foo"-prune

关于linux - 如何使用 "find"命令限制对目录的搜索?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49833998/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com