Search code examples
linuxsh

sh loop for all files in a directory and sub-directories matching a pattern


I want to loop through files matching a pattern. They can be in the current directory or sub directories.

I tried:

 for file in **/$_pat*; do

but it only finds files in sub directories. I also put the following command in bashrc and also in the script but it still doesn't work.

shopt -s globstar

shopt isn't recognized in the script.

shopt: not found                              

Solution

  • Use find:

    find "$_path" -type f -iname "*your_pattern*"
    

    Where:

    -iname = case insensitive matching of a pattern

    -type f = searches only regular files, omitting directories or links

    To use it in a loop:

    find "$_path" -type f -iname "*your_pattern*"|while read file
    do
    echo "$file"
    done
    

    for loop will not work if you have spaces in the results, while while reads each while line

    Depending on what you want to do a an end goal, you can use the -exec in find like:

    find "$_path" -type f -iname "*your_pattern*" -exec echo {} \;
    

    where {} would represent the matching line/file`

    Also you do ned the \; at the end