Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top
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
share|improve this question
up vote 5 down vote accepted

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 {} \;
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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