Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through subdirectories in bash

Tags:

grep

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?

like image 887
123Ex Avatar asked Dec 23 '10 04:12

123Ex


2 Answers

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).

like image 170
Dennis Williamson Avatar answered Nov 08 '22 09:11

Dennis Williamson


Well, you can do that using grep:

grep -rl ^ /path/to/dir

But why? find is better.

like image 35
Dallaylaen Avatar answered Nov 08 '22 09:11

Dallaylaen