CLI tip 23: recursive filename matching with globstar
Enable the globstar
option to recursively match filenames within a specified path. You can use shopt -s globstar
and shopt -u globstar
to set and unset this option respectively.
First, create some sample files:
$ mkdir test_globstar && cd $_
$ mkdir -p todos projects/{tictactoe,calculator}
$ touch ip.txt .hidden.txt report.log hello.py
$ touch todos/{books,outing}.txt
$ touch projects/tictactoe/game.py projects/calculator/{calc.sh,notes.txt}
Here are some examples:
$ shopt -s globstar
$ ls -1 **/*.txt
ip.txt
projects/calculator/notes.txt
todos/books.txt
todos/outing.txt
$ ls -1 **/*/*.txt
projects/calculator/notes.txt
todos/books.txt
todos/outing.txt
# assumes extglob is enabled
$ ls -1 **/*.@(py|sh)
hello.py
projects/calculator/calc.sh
projects/tictactoe/game.py
$ ls -1d **/
projects/
projects/calculator/
projects/tictactoe/
todos/
If you need to match hidden files as well, enable the
dotglob
option:$ shopt -s dotglob $ ls -1 **/*.txt .hidden.txt ip.txt projects/calculator/notes.txt todos/books.txt todos/outing.txt
Video demo:
See also my Linux Command Line Computing ebook.