In this tutorial, we are going to learn how to use globbing, a feature available in Unix/Linux systems, to select multiple files based on a pattern. Globbing makes use of wildcard characters to match file patterns in shell scripts.
By the end of this tutorial, you will learn:
- What globbing is and how it works
- How to use wildcard characters to match file patterns
- Write shell scripts using globbing
Prerequisites:
- Basic knowledge of Linux/Unix shell commands
- Familiarity with basic programming concepts
Globbing is a method used in Unix/Linux to select filenames based on patterns containing wildcard characters. The wildcard characters used in globbing are *
, ?
, and []
.
*
matches any number of any characters including none.?
matches any single character.[]
matches any single character specified within the brackets.Let's dive into examples to understand these wildcard characters.
*
WildcardIn the code snippet below, we are using the *
wildcard to match all files with .txt
extension.
# List all .txt files in the current directory
ls *.txt
Here, *
matches any number of any characters, and .txt
specifies that we are only interested in files that end with .txt
.
?
WildcardIn this example, we use the ?
wildcard to match files of a specific pattern.
# List all files in the current directory with a single character name
ls ?
Here, ?
matches any single character. So, this command will list files such as a
, 1
, _
, etc.
[]
WildcardHere, we use the []
wildcard to match files starting with either 'a', 'b', or 'c'.
# List all files in the current directory starting with a, b, or c
ls [abc]*
In this case, [abc]
matches any single character specified within the brackets, i.e., 'a', 'b', or 'c'; and *
matches any number of any characters.
Please note that the actual output of these commands will depend on the files present in your directory.
In this tutorial, we learned about globbing, a method used in Unix/Linux to select filenames based on patterns containing wildcard characters. We also learned how to use the wildcard characters *
, ?
, and []
to match file patterns.
To further enhance your understanding of globbing, try to write more complex file patterns and use different wildcard characters together.
Solutions:
ls *.{jpg,png}
{jpg,png}
to match either .jpg or .png files.ls [0-9]*
[0-9]
matches any single digit, i.e., any number from 0 to 9.ls ??
??
matches any two characters.Remember, the best way to learn is by doing. So, keep practicing until you are comfortable with using globbing to match file patterns.