Home > Software engineering >  for-loop for filename that have a specific string or a specific extension
for-loop for filename that have a specific string or a specific extension

Time:06-16

  • On a for-loop how do you search for both a specific string or a filename extension?

I have files that have no extension but have the string "-DT-" in the filename, and other files that have the extension .fff. I want to process both types.

local dir imfiles

for imfiles in "$dir"**/*-DT-!(.jpg); do
   printf "File processed: ${imfiles}\n"
done
  • How can I make the for-loop to not only look for files that have the string -DT- but also files that have an extension .fff?

The result would be the for-loop processing both types of files. I have tried using an array, but it didn't work. I have seen a lot of examples of for-loop but none approaching this specific scenario.

CodePudding user response:

Try

shopt -s dotglob extglob nullglob globstar

for imfiles in "$dir"**/@(*-DT-!(*.jpg)|*.fff); do
   printf "File processed: ${imfiles}\n"
done

CodePudding user response:

As the two groups don't overlap, you can specify one after the other:

for imfile in "$dir"/*-DT-!(*.*) *.fff ; do

CodePudding user response:

One idea using find to locate the desired files (assuming all files located under the same $dir):

while read -r imfiles 
do
    printf "File processed: ${imfiles}\n"
done < <(find "${dir}" -name "*-DT-*" -o -name "*.fff" 2>/dev/null)

If the files are under different directories then chain 2 find calls together, eg:

while read -r imfiles 
do
    printf "File processed: ${imfiles}\n"
done < <(find "${dir}" -name "*-DT-*" 2>/dev/null; find . -name "*.fff" 2>/dev/null)

NOTE: adjust the find command as needed, eg, do not search in sub-directories, look for files of specific size, etc.

  • Related