Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash Pattern Matching

I'm trying to use pattern matching to find all files within a directory that have an extension of either .jpg or jpeg.

ls *.[jJ][pP][eE][gG] <- this obviously will only find the .jpeg file extension. The question is, how do I make the [eE optional?

like image 602
Elliot Avatar asked Oct 18 '11 10:10

Elliot


2 Answers

Match harder.

ls *.[jJ][pP]{[eE],}[gG]
like image 141
Ignacio Vazquez-Abrams Avatar answered Oct 11 '22 12:10

Ignacio Vazquez-Abrams


As well as the standard (simple) glob patterns, bash ≥4.0 has extended globbing.
It is off by default. To turn it on, use: shopt -s extglob

With extglob you have access to extended regular expression patterns as well as the standard patterns. Furthermore, in your particular situation, you can tailor your glob's behaviour even further by enabling a case insensitive glob, which is also off by default. To turn it on, use: shopt -s nocaseglob

Enabling extglob does not alter how standard globs work. You can mix the two forms. The only issue is that you have to be aware of the special extended regex syntax. eg, In the example below, the only part of it which is an extended regex, is ?(e). The rest is standard glob expansion, with case-insensitivity enabled.

The extended-regex, case-insensitive glob for your situation is:

shopt -s extglob nocaseglob
ls -l *.jp?(e)g

You can find more info and examples at: Bash Extended Globbing.

like image 2
Peter.O Avatar answered Oct 11 '22 10:10

Peter.O