Applying Wildcards for File Operations
Using the Wildcard *
The *
wildcard matches zero or more characters. It can be used to perform various file operations, such as:
$ ls *.txt ## List all files with .txt extension
$ cp *.jpg backup/ ## Copy all .jpg files to the backup directory
$ rm *.pyc ## Remove all .pyc files
Using the Wildcard ?
The ?
wildcard matches a single character. It can be used to perform operations on files with a specific pattern, such as:
$ ls file?.txt ## List files like file1.txt, file2.txt, etc.
$ mv file?.bak file?.txt ## Rename all .bak files to .txt
$ find . -name 'file?.pdf' -exec cp {} backup/ \; ## Copy all PDF files to the backup directory
Using Character Ranges with []
The []
wildcard allows you to match a range or set of characters. This can be useful when working with files with a specific pattern, such as:
$ ls file[0-9].txt ## List files like file0.txt, file1.txt, ..., file9.txt
$ rm report[a-z].log ## Remove all log files with names like reporta.log, reportb.log, etc.
$ cp image[!0-9].png backup/ ## Copy all PNG files except those with numbers in the name
Combining Wildcards
You can also combine multiple wildcards to create more complex patterns, for example:
$ ls *.{jpg,png} ## List all .jpg and .png files
$ find . -name 'file[0-9]_*.txt' -exec cat {} \; ## Display the contents of all text files with a numeric prefix
$ mv *_[0-9][0-9][0-9].* archive/ ## Move all files with a 3-digit numeric suffix to the archive directory
By understanding and practicing the use of these wildcards, you can streamline your file management tasks and become more efficient in your Linux workflow.