1
arrFormat=( jpg jpeg bmp tiff png )
varExtension="jpg"

for elem in "${arrFormat[@]}"
do
  echo "${elem}"
  # do something on $elem #
done


#for i in $( find -E . -iregex '.*\.($arrFormat)' )  ; do   #problem
#for i in $( find -E . -iregex '.*\.("$arrFormat")' )  ; do #problem
#for i in $( find -E . -iregex '.*\.($varExtension)' )  ; do        #problem
#for i in $( find -E . -iregex '.*\.("$varExtension")' )  ; do  #problem

for  i in $( find -E . -iregex '.*\.(jpg|png)' )  ; do # this works fine

  echo "${i}"
  # do something on $i #
done

So it seems that the regular expression has a problem with variable(s) How can I give an array or just one variable as argument to a regular expression

Shell info, MACINTOSH :

Darwin Kernel Version 15.3.0: Thu Dec 10 18:40:58 PST 2015; root:xnu-3248.30.4~1/RELEASE_X86_64 x86_64
5

The problem are the single quotes. Variables aren't expanded in single quotes (from man bash):

Enclosing characters in single quotes preserves the literal value of each character within the quotes.

If you want to use a variable, you need double quotes. To illustrate:

$ foo="bar"
$ echo '$foo'
$foo
$ echo "$foo"
bar

So, in your case, you want something like:

for i in $( find -E . -iregex ".*\.$varExtension")  ; do  

Or, better since the above can't deal with strange file names:

find -E . -iregex ".*\.$varExtension" -print0 | while IFS= read -r -d '' i; do

Or, forget the loop and have find do whatever the job is for you:

find -E . -iregex ".*\.$varExtension" -exec something {} \;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.