Bash Tips: Wildcards
Many text mode guerrillas use Bash on a daily basis, almost always with some form of “globbing” (aka. “pattern matching” or “wildcards”). From what I’ve seen, this is usually limited to the asterisk, as in ls -l adam*.jpg, or worse, just ls -l adam*. (”Worse” being synonymous with “less explicit” in this definition.)
The asterisk is a perfectly valid wildcard, but it’s not the only one: the question mark is pretty useful as well. It will match a single character, as opposed to any number of characters:
adam@aziz:~$ ls
file-index.txt file1.txt file3.jpg file4.txt file6.jpg
file-summary.txt file2.jpg file3.txt file5.jpg file6.txt
file1.jpg file2.txt file4.jpg file5.txt
adam@aziz:~$ ls file?.txt
file1.txt file2.txt file3.txt file4.txt file5.txt file6.txt
Pretty nice, but we can get even more explicit. What if we only want the first three text files?
adam@aziz:~$ ls file[1-3].txt
file1.txt file2.txt file3.txt
Or the first three text files and their corresponding images?
adam@aziz:~$ ls file[1-3].{txt,jpg}
file1.jpg file1.txt file2.jpg file2.txt file3.jpg file3.txt
The curly brace above will expand the touching glob into a new word. The glob a{1,2} becomes a1 a2. This is very hand for moving files with long, complicated names:
adam@aziz:~$ mv long_name_that_autocompleted_poorly{1,2}.txt
That would rename long_name_that_autocompleted_poorly1.txt to long_name_that_autocompleted_poorly2.txt. Note that you’re not limited to just two values in the braces, and you can have a blank value.
The curly braces also work in tcsh! Neat tip!
Hi dot.dot.dot!
I’d like to ask you, whether it is possible to use wildcard function in Makefile dependencies. I’ve tried to, but it seemed not to work as I had expected.
Makefile:
map.txt : \
$(wildcard file.{nn,vb,adj}
… action
> touch file.nn
> make map.txt
map.txt is up-to-date
Not sure, though I’m not familiar with all the ins and outs of makefiles. When I have complicated Makefile requirements, I usually generate (by hand) a custom configure.sh that creates all the necessary declarations.