I'm writing a bash script that needs to loop files inside a directory that do not match a specific extension. So far, I've found that the following code loops all files that matches the given extension:
for f in *.txt ; do
    echo $f;
done
How could insthead loop through files that do not match the specified extension?
You can pattern-match with the == operator.
for f in *; do
    [[ $f == *.txt ]] && continue
    # [[ $f != *.txt ]] || continue
    ...
done
If this might run in an empty directory, either use shopt -s nullglob prior to the loop, or put [ -e "$f" ] || continue in side the loop. (The former is preferable, as it avoids constantly checking if a file exists.)
to loop files inside a directory that do not match a specific extension
You can use extglob:
shopt -s extglob
for f in *.!(txt); do
    echo "$f"
done
pattern *.!(txt) will match all entries with a dot and no txt after the dot.
EDIT: Please see comments below. Here is a find version to loop through files in current directory that don't match a particular extension:
while IFS= read -d '' -r f; do
    echo "$f"
done < <(find . -maxdepth 1 -type f -not -name '*.txt' -print0)
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With