Search code examples
bashglob

Matching *.jpg but not *.foo.jpg in bash


This must be simple but I can't figure it out.

for filename in *[^\.foo].jpg
do
echo $filename
done

Instead of the matched filenames, echo shows the pattern:

+ echo '*[^.foo].jpg'
*[^.foo].jpg

Intention is to find all files ending in .jpg but not .foo.jpg.

EDIT: Tried this as per (misunderstood) advice:

for filename in *[!".foo"].jpg

Still not there!


Solution

  • You actually can do this, with an extglob. To demonstrate, copy-and-paste the following code:

    shopt -s extglob
    cd "$(mktemp -d "${TMPDIR:-/tmp}/test.XXXXXX")" || exit
    touch hello.txt hello.foo hello.foo.jpg hello.jpg
    printf '%q\n' !(*.foo).jpg
    

    Output should be:

    hello.jpg