Start Coding

Topics

Bash Wildcards and Globbing

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.

What are Wildcards?

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.

Common Wildcard Characters

  • * - 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 brackets

Globbing Patterns

Globbing 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.

Examples of Wildcard Usage


# 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]*
    

Advanced Globbing Techniques

Bash offers extended globbing options that provide even more flexibility in pattern matching. To enable these features, use the shopt -s extglob command.

Extended Globbing Patterns

  • ?(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

Extended Globbing Example


# Enable extended globbing
shopt -s extglob

# Remove all files except .txt and .log files
rm !(*.txt|*.log)
    

Considerations and Best Practices

  • Always test your wildcard patterns before using them with destructive commands like rm.
  • Use quotes around wildcard patterns to prevent unexpected expansion by the shell.
  • Be aware that hidden files (starting with a dot) are not matched by default. Use .* to include them.
  • Combine wildcards with other Bash Command Line Interface features for powerful file manipulation.

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.

Related Concepts