简体   繁体   中英

Iterate through subdirectories in bash

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?

This will go one subdirectory deep. The inner for loop will iterate over enclosed files and directories. The if statement will exclude directories. You can set options to include hidden files and directories ( 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 -maxdepth option.

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

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

你可能正在寻找find(1)

Well, you can do that using grep :

grep -rl ^ /path/to/dir

But why? find is better.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM