Helfenstein
Helfenstein

Reputation: 315

Exclude filenames with certain prefix in for loop (globbing)

This is probably quite easy, but I can't figure it out. In a for loop I want to exclude certain files with the prefix zz (e.g. zz131232.JPG) but I don't know how to exclude these files.

for i in *.JPG; do
    # do something
done

How do I modify the 'for rule' to exclude files with the prefix zz?

Upvotes: 5

Views: 526

Answers (2)

Adrian Frühwirth
Adrian Frühwirth

Reputation: 45526

If you are dealing with many files you can also use GLOBIGNORE or extended globbing to avoid expanding the files you wish to skip in the first place (which might be faster):

GLOBIGNORE='zz*'
for file in *.JPG; do
    do_something_with "${file}"
done
# save and restore GLOBIGNORE if necessary

or

shopt -s extglob # enable extended globbing
for file in !(zz*).JPG; do
    do_something_with "${file}"
done
shopt -u extglob # disable extended globbing, if necessary

Note that if there are no .JPG files in the current directory the loop will still be entered and $i be set to the literal *.JPG (in your example), so you either need to check if the file exists inside the loop or use the nullglob option.

for file in *.JPG; do
    [ -e "${file}" ] || continue
    do_something_with "${file}"
done

or

shopt -s nullglob
for file *.JPG; do
    do_something_with "${file}"
done
shopt -u nullglob # if necessary

Try the following in your shell to understand what happens without nullglob:

$ for f in *.doesnotexist; do echo "$f"; done
*.doesnotexist

Upvotes: 1

Reinstate Monica Please
Reinstate Monica Please

Reputation: 11583

Something like

for i in *.JPG; do
  [[ $i != "zz"* ]] && echo "$i"
done

or skip them:

for i in *.JPG; do
  [[ $i == "zz"* ]] && continue
  # process the other files here
done

Upvotes: 4

Related Questions