Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: loop through files that DO NOT match extension

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?

like image 881
oniramarf Avatar asked May 16 '16 16:05

oniramarf


2 Answers

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.)

like image 183
chepner Avatar answered Sep 18 '22 21:09

chepner


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)
like image 29
anubhava Avatar answered Sep 19 '22 21:09

anubhava