我正在尝试制作一个bash脚本,该脚本将创建指向具有“target”子目录的目录的符号链接。我使用“find”命令搜索“target”目录并将文件路径放入数组。
array_of_dirs=( $(find -type d -name "target") )
数组是循环的,符号链接是指向目录的。
我的问题是目录结构的深度未知,子目录可以有多个“目标”目录。
目录结构可以是:
.
├── 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
在找到这些路径时,会创建不需要的符号链接。
./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。当然,它需要否定-而不是路径“/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
选项路径…-梅干似乎也有同样的效果。有关详细的差异,请仔细阅读本手册。一个简短的测试显示使用prune有10%的时间效益,但它可能是缓存效果或随机影响。
(不必要的冗长中间溶液:)
find-type d-name“foo”-路径“/foo”-修剪
关于linux - 如何使用“find”命令限制对目录的搜索?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49833998/