Using Bash Wildcards

Last Updated: 

In order to rename a mispelled file from the command line, one will use mv. Though, when you have a large list of files to move from one directory to another, iterating through a serie of mv old_file new_file may be error prone and not very efficient. Instead, you can leverage the Bash wildcards which can be used as globbing patterns or regular expressions.

Most used wildcard is the asterix * (match all characters) but other usefull wildcards exist like the question mark ? that match for a single character. In some case, as a large directories, that's avoid you to use a grep on your ls command and give you a more concise listing.

Below we will go over few examples of globbing and regex.

Question Mark Wildcard "?"

[root@host ~]$ ls
pic1.jpg pic1.txt pic2.jpg pic3.jpg pic4.jpg pic5.jpg pic-big.jpg pic.jpg pic-small.jpg pic.txt pic1.txt pic2.txt pic1.bmp  

[root@host ~]$ ls pic?.jpg
pic1.jpg pic2.jpg pic3.jpg pic4.jpg pic5.jpg

Another useful wildcard will be the square brackets [] and curly brackets {}. The first one let you match a range of values, while the second let you define a list of values.

Square Brackets Wildcard "[]" and Curly Brackets Wildcard "{}"

[root@host ~]$ ls pic[1-3].jpg
pic1.jpg pic2.jpg pic3.jpg

[root@host ~]$ ls pic1.{txt,jpg,bmp}
pic1.txt pic1.jpg pic1.bmp

You can use those wildcards simultanously for a better search.

[root@host ~]$ ls pic[1-3].{txt,jpg}
pic1.jpg pic1.txt pic2.jpg pic3.jpg

We have seen how to perform our ls search but you can also use those bash wildcards with any of your Bash commands.

# Example 1
[root@host ~]$ ls
a_too_short_file_name_with_lot_of_ch4r4ct3r3.txt

[root@host ~]$ mv a_too_{short,long}_file_name_with_lot_of_ch4r4ct3r3.txt

[root@host ~]$ ls
a_too_long_file_name_with_lot_of_ch4r4ct3r3.txt

# Example 2
[root@host ~]$ ls
dest     pic1.jpg pic2.jpg pic3.jpg

[root@host ~]$ cp pic[1-3].jpg dest

[root@host ~]$ ls dest/
pic1.jpg pic2.jpg pic3.jpg

👉 Read more about Braces Expansion in the post Printing a Sequence of Letters or Numbers

Related bash posts that you may like
What is the Bash Null Command?
Learn about the Bash null command, also known as the POSIX shell colon command. This post cover concrete use cases and pitfalls to avoid.
How To Format Date and Time in Linux, macOS, and Bash?
Find out how to manipulate date and time on linux and macOS systems as well as natively in the Bash shell. This post covers all you need to know to format a date from your shell.
How To Use Option as Meta Key in macOS Terminal?
The Meta Key is a modifier key that can be quite helpful to improve your productivity while working in a terminal and bash. This post cover how to enable from the command line the Meta Key in macOS Terminal.