遍历 bash 中的子目录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4515866/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 23:09:27  来源:igfitidea点击:

Iterate through subdirectories in bash

bashgrep

提问by 123Ex

How can we iterate over the subdirectories of the given directory and get file within those subdirectories in bash. Can I do that using grep command?

我们如何遍历给定目录的子目录并在 bash 中获取这些子目录中的文件。我可以使用 grep 命令来做到这一点吗?

回答by Paused until further notice.

This will go one subdirectory deep. The inner forloop will iterate over enclosed files and directories. The ifstatement will exclude directories. You can set options to include hidden files and directories (shopt -s dotglob).

这将深入一个子目录。内部for循环将遍历封闭的文件和目录。该if语句将排除目录。您可以设置选项以包含隐藏文件和目录 ( shopt -s dotglob)。

shopt -s nullglob
for dir in /some/dir/*/
do
    for file in "$dir"/*
    do
        if [[ -f $file ]]
        then
            do_something_with "$file"
        fi
    done
done

This will be recursive. You can limit the depth using the -maxdepthoption.

这将是递归的。您可以使用该-maxdepth选项限制深度。

find /some/dir -mindepth 2 -type f -exec do_something {} \;

Using -mindepthexcludes files in the current directory, but it includes files in the next level down (and below, depending on -maxdepth).

使用-mindepth排除当前目录中的文件,但它包括下一级(及以下,取决于-maxdepth)的文件。

回答by earl

You are probably looking for find(1).

您可能正在寻找find(1)

回答by Dallaylaen

Well, you cando that using grep:

好吧,你可以使用grep

grep -rl ^ /path/to/dir

But why? findis better.

但为什么?find更好。