Exclude file names with a specific prefix in the for (globbing) loop

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

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

How to change the rule "for rule" to exclude files with a prefix zz?

+4
source share
2 answers

Sort of

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
+3
source

If you are dealing with many files, you can also use GLOBIGNOREor extended globbingto avoid expanding the files you want to skip in the first place (which can 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

, .JPG, , $i *.JPG ( ), , nullglob.

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

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

, , nullglob:

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

Source: https://habr.com/ru/post/1525309/


All Articles