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:
annika@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
annika@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?
annika@aziz:~$ ls file[1-3].txt
file1.txt file2.txt file3.txt
Or the first three text files and their corresponding images?
annika@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:
annika@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.