Wildcards and globbing are powerful features in Bash that allow you to work with multiple files or directories using pattern matching. These techniques can significantly enhance your productivity when working with the command line.
Wildcards are special characters that represent one or more other characters. They act as placeholders in file names or paths, enabling you to perform operations on multiple files simultaneously.
*
- Matches any number of characters (including none)?
- Matches exactly one character[...]
- Matches any single character within the brackets[!...]
or [^...]
- Matches any single character not within the bracketsGlobbing is the process of expanding wildcard patterns into a list of matching file names or paths. Bash performs globbing automatically when you use wildcards in commands.
# List all .txt files in the current directory
ls *.txt
# Remove all files starting with 'temp'
rm temp*
# Copy all files with a three-letter extension
cp *.??? /destination/folder/
# List all files starting with a letter from a to m
ls [a-m]*
Bash offers extended globbing options that provide even more flexibility in pattern matching. To enable these features, use the shopt -s extglob
command.
?(pattern)
- Matches zero or one occurrence of the pattern*(pattern)
- Matches zero or more occurrences of the pattern+(pattern)
- Matches one or more occurrences of the pattern@(pattern)
- Matches exactly one occurrence of the pattern!(pattern)
- Matches anything except the pattern
# Enable extended globbing
shopt -s extglob
# Remove all files except .txt and .log files
rm !(*.txt|*.log)
rm
..*
to include them.Mastering wildcards and globbing can significantly improve your efficiency when working with Bash File Manipulation tasks. These techniques are essential for any Bash user, from beginners to advanced scripters.