提取包含具有匹配字符串的文件的目录路径

ram*_*ran 2 grep directory find files

我在多个级别有多个子目录,其中包含一个文件 results.out

./dir1/results.out
./dir2/dir21/results.out
./dir3/dir31/dir311/results.out
Run Code Online (Sandbox Code Playgroud)

现在,我需要寻找string1results.out和这些提取的目录路径results.out包含string1,因为我需要这些子目录移动到另一个位置。例如,我可以使用以下代码获取文件路径

for i in $(find . -type f -name "results.out);
do
grep -l "string1" $i
done
Run Code Online (Sandbox Code Playgroud)

如何修改上面的代码只获取目录路径?

ste*_*ver 5

如果您有 GNU find,则可以使用%h格式说明符打印路径

    %h     Leading directories of file's name (all but the last ele?
           ment).  If the file name contains no slashes (since it is
           in  the  current  directory)  the %h specifier expands to
           ".".
Run Code Online (Sandbox Code Playgroud)

所以例如你可以做

find . -name 'results.out' -exec grep -q 'string1' {} \; -printf '%h\n'
Run Code Online (Sandbox Code Playgroud)