我想在文件内容中递归地搜索子目录,但我只关心第一级子目录是否包含任何匹配项。也就是说,给定:
ParentDirectory
Subdirectory1
File containing match
File not containing match
File containing match
Subdirectory2
File not containing match
File not containing match
Subdirectory3
File not containing match
Subdirectory3.1
File containing match
我需要知道:
Matches:
ParentDirectory/Subdirectory1
ParentDirectory/Subdirectory3
有人可以提供一种使用 grep 或类似实用程序来执行此操作的方法吗?
答案1
用于在每个子目录上find
运行递归:grep
echo "Matches:"
find ParentDirectory -mindepth 1 -maxdepth 1 -type d \
-exec grep -rq pattern {} \; \
-and -print
-q
选项让grep
在第一个匹配处停止
-and -print
将仅在找到某些内容find
时才打印目录。grep
使用for
-loop 的替代方案:
echo "Matches:"
for d in ParentDirectory/* ; do
[ -d "$d" ] && grep -rq pattern "$d" && echo "$d"
done
任一版本的输出:
Matches:
ParentDirectory/Subdirectory1
ParentDirectory/Subdirectory3