CLI tip 19: extended globs
The Bash shell provides extglob
option for advanced pattern matching of filenames. These will help you apply regexp like quantifiers, provide alternate patterns and negation. From man bash
:
Extended glob | Description |
---|---|
?(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 |
Extended globs are disabled by default. You can use shopt -s extglob
and shopt -u extglob
to set and unset this option respectively.
Here are some examples (visit globs.sh to get the script used below).
$ source globs.sh
$ ls
100.sh f1.txt f4.txt hi.sh math.h report-02.log
42.txt f2_old.txt f7.txt ip.txt notes.txt report-04.log
calc.py f2.txt hello.py main.c report-00.log report-98.log
# one or more digits followed by '.' and then zero or more characters
$ ls +([0-9]).*
100.sh 42.txt
# same as: ls *.c *.sh
$ ls *.@(c|sh)
100.sh hi.sh main.c
# not ending with '.txt'
$ ls !(*.txt)
100.sh hello.py main.c report-00.log report-04.log
calc.py hi.sh math.h report-02.log report-98.log
# not ending with '.txt' or '.log'
$ ls *.!(txt|log)
100.sh calc.py hello.py hi.sh main.c math.h
Video demo:
See also my Linux Command Line Computing ebook.