Removing Multiple Files Using Wildcards
Often, you need to remove multiple files at once. Linux provides wildcards to make this task easier. Wildcards are special characters that can represent one or more characters in a filename.
Let's look at the common wildcards:
* (asterisk): Matches any number of characters (including zero)
? (question mark): Matches exactly one character
[] (square brackets): Matches any character within the brackets
First, let's check the current files in the old_predictions directory:
ls ~/project/old_predictions
You should see:
prediction-02.txt prediction-03.txt prediction-04.txt prediction-05.txt
Now, let's remove files prediction-02.txt, prediction-03.txt, and prediction-04.txt all at once. We can use pattern matching with curly braces {} to specify multiple options:
rm ~/project/old_predictions/prediction-{02..04}.txt
This command uses the range notation {02..04} which expands to 02, 03, 04. The shell expands this command before execution, effectively running:
rm ~/project/old_predictions/prediction-02.txt ~/project/old_predictions/prediction-03.txt ~/project/old_predictions/prediction-04.txt
Another common approach is using the asterisk wildcard. For example, if you wanted to remove all prediction files, you could use:
## This is just an example - don't run this command now
## rm ~/project/old_predictions/prediction-*.txt
Let's check what files remain in the directory:
ls ~/project/old_predictions
You should now only see:
prediction-05.txt
This shows that the three files were successfully removed, and only prediction-05.txt remains.