Using curly brace expansion in an if statement

Let's say I have a list with filenames in it with date. I want to do something with files with a png or jpg extension of a specific date. I have the following code:

year="2015"
for f in $myFiles
do
    if [[ $f = *"$year"{".png",".jpg"} ]]
    then
        echo $f
    fi
done

      

It doesn't work, the file doesn't pass the condition. I could do this using two conditions and using a condition or

; but I was wondering what I was doing wrong. Brace expansion should work, otherwise how to use it.

+3


source to share


3 answers


{...}

does not expand for a condition if

. You can use extglob

:

shopt -s extglob

[[ $f = *"$year".@(png|jpg) ]] && echo "$f"

      



You may not even need a for loop with extglob

, you can simply do:

printf "%s\n" *"$year".@(png|jpg)

      

+2


source


You can use Bash regex matching:

pat="(.*)($year)(\.png|\.jpg)"
...
if [[ $f =~ $pat ]]

      



Example:

year="2015"
pat="(.*)($year)(\.png|\.jpg)"
for f in $myFiles
do
    if [[ $f =~ $pat ]]
    then
        ext="${BASH_REMATCH[3]}" # This is the extension, .png or .jpg
        # Additionally ${BASH_REMATCH[1]} is the part before $year in $f.
        echo "$f" "$ext"
    fi
done

      

+2


source


You can also use the parameter / substring expansion extension to build your test:

year="2015"
for f in $myFiles
do
    if [ x${f##*${year}.jpg} = x -o x${f##*${year}.png} = x ]
    then
        echo $f
    fi
done

      

Note. x

just appended to both sides of the test to avoid checking for empty string (e.g. instead of "${f##*${year}.jpg}" = ""

)

+1


source







All Articles