
Navigating the Linux command line becomes significantly more efficient when you understand how to use wildcards. These special characters allow you to select multiple files or directories based on patterns, saving you time and effort. Let's explore how they work.
Understanding Wildcards:
* (Asterisk): Matches zero or more characters.
Example: *.txt matches all files ending with ".txt".
Example: data* matches files starting with "data".
? (Question Mark): Matches any single character.
Example: file?.txt matches files like "file1.txt" or "fileA.txt".
[] (Square Brackets): Matches any single character within the specified range or set.
Example: file[1-3].txt matches "file1.txt", "file2.txt", and "file3.txt".
Example: file[abc].txt matches "filea.txt", "fileb.txt", and "filec.txt".
[!...] or [^...] (Negated Square Brackets): Matches any single character not within the specified range or set.
Example: file[!1-3].txt matches "file4.txt" and "fileA.txt" but not "file1.txt", "file2.txt", or "file3.txt".
Practical Examples:
Listing Files:
$ ls *.txt (Lists all text files in the current directory)
$ ls file?.txt (Lists files like "file1.txt", "fileA.txt")
$ ls data[1-5].txt (Lists files like "data1.txt", "data2.txt", etc., up to "data5.txt")
$ ls data[!a-c].txt (Lists files that start with data, and do not end with a,b, or c)
Copying Files:
$ cp *.txt backup/ (Copies all text files to the "backup" directory)
Removing Files:
$ rm data*.log (Removes all log files starting with "data")
Practice Session 1: With Examples
Create Files:
$ touch file1.txt file2.txt fileA.txt data1.log data2.log report.doc
List all ".txt" files:
$ ls *.txt (Output: file1.txt file2.txt fileA.txt)
List files starting with "file" and having a single character after "file":
$ ls file?.txt (Output: file1.txt file2.txt fileA.txt)
List log files starting with data:
$ ls data*.log (Output: data1.log data2.log)
Copy all log files to directory backup (create backup directory first):
$ mkdir backup
$ cp *.log backup/
$ ls backup (Output: data1.log data2.log)
Remove all doc files:
$ rm *.doc
Practice Session 2: Without Examples
Create a set of files:
Create files with names like "image1.jpg", "image2.jpg", "imageA.png", "document1.pdf", "documentB.pdf", "report.txt", "temp1.tmp", and "temp2.tmp".
List all files with the ".jpg" extension.
List files starting with "document" followed by a single character.
List files that start with "temp" and end with ".tmp".
Copy all ".pdf" files to a directory named "pdfs" (create the directory first).
Remove all files with the ".tmp" extension.
List all files that start with image but do not end with a number.
By mastering wildcards, you'll significantly enhance your Linux command-line proficiency.
コメント