How to get the list of files of specific extension in bash in just one line?

1.8k Views Asked by At

This is how I can get *.png files from the positive folder sub-directories:

FILES=./positive/*/*.png

How to modify this command to get both *.png, *.jpg and *.bmp files? Just one line.

2

There are 2 best solutions below

4
On BEST ANSWER

You could just use find:

find ./positive/ -name *.png

In order to use it for *.png*, *.jpg and *.bmp, you may take advantage of -o option which stands for "or" keyword. With it, you can join a few -name <NAME> expressions:

find ./positive/ -name *.png -o -name *.jpg -o -name *.bmp

or alternatively (if you are keen on graphical or operator):

find ./positive/ -name *.png || -name *.jpg || -name *.bmp

Furthermore, if you are not certain that all of the files have lowercase names - you may need to use -iname (case insensitive) option instead of -name.

2
On
shopt -s extglob                     # enable extended globbing
ls ./positive/*/*.@(png|jpg|bmp)

?(pattern-list): Matches zero or one occurrence of the given patterns

*(pattern-list): Matches zero or more occurrences of the given patterns

+(pattern-list): Matches one or more occurrences of the given patterns

@(pattern-list): Matches one of the given patterns

!(pattern-list): Matches anything except one of the given patterns

Source: http://www.linuxjournal.com/content/bash-extended-globbing


To fill an array:

shopt -s extglob
files=( ./positive/*/*.@(png|jpg|bmp) )
for f in "${files[@]}"; do echo "$f"; done