Bash中如何跨层级查找包含指定文件的目标目录
跨层级查找特定目录下的目标文件
我需要在Bash环境中查找任意层级下,位于dir03目录中的myfile.txt文件,示例目录结构如下:
dir01/dir02/dir03/myfile.txt dir01/dir03/ ##该目录无目标文件 dir01/dir04/dir05/dir03/myfile.txt dir01/dir04/dir05/dir06/myfile.txt ##不需要此结果
我尝试过以下几种命令,但都存在问题:
- 执行
find ./dir01 -type d -iname "dir03":会返回所有名为dir03的目录,包括不含目标文件的目录,不符合需求。 - 执行
find ./dir01/*/dir03 -iname "myfile.txt":无法匹配更深层级的目标文件(比如dir01/dir04/dir05/dir03/myfile.txt)。 - 执行
find ./dir01 -iname "dir03/myfile.txt":直接报错,提示信息如下:
find: warning: Unix filenames usually don't contain slashes (though pathnames do). That means that '-iname ‘dir03/myfile.txt’' will probably evaluate to false all the time on this system. You might find the '-wholename' test more useful, or perhaps '-samefile'. Alternatively, if you are using GNU grep, you could use 'find ... -print0 | grep -FzZ ‘dir03/myfile.txt’'
目前我能实现需求的方法,但在复杂目录结构下效率较低:
find ./dir01 -iname "myfile.txt" -print0 | grep -FzZ 'dir03' | sed "s/myfile\.txt/\n/g"
该命令先找出所有myfile.txt,再筛选位于dir03下的结果,最后拆分换行。
补充方法:
find ./dir01 -iname "myfile.txt" > myres0.txt grep 'dir03' myres0.txt > myres1.txt
如果要查找多个目标父目录,还可以用包含目录列表的文件筛选:
grep -f mytargetDirs.txt myres0.txt > myres1.txt
我想知道有没有更简便、高效的方法,能直接通过find命令跨任意层级查找dir03/myfile.txt这类路径的文件?
注:示例目录名仅作演示,实际目录无相同前缀。
内容的提问来源于stack exchange,提问作者Max_IT
相关产品推荐
相关产品推荐

