I'm looking for a way to delete all JPG files in a folder while keeping three specific ones: DSC1011.jpg, Dsc1015.jpg, and Dsc1020.jpg. What's the best command to achieve that? I really appreciate any help from the community!
5 Answers
Another option is to use extended globbing. First, enable it with:
```bash
shopt -s extglob
```
Then run:
```bash
ls -l !(DSC1011.jpg|Dsc1015.jpg|Dsc1020.jpg)
```
If that shows you the files you want to delete, you can use a similar command with `rm` to actually delete them.
If you're comfortable with loops, try this:
```bash
for file in *.jpg; do
[[ "$file" != "DSC1011.jpg" && "$file" != "Dsc1015.jpg" && "$file" != "Dsc1020.jpg" ]] && rm "$file"
done
```
It's a straightforward way to handle it, and it works well!
Wow, that looks powerful! I'll have to try it out.
Just a heads-up: you can clean it up a bit and make it more readable by using `if` instead of `&&`.
You can use the `find` command for this! Start by testing the command to make sure you have the right files identified:
```bash
find . -type f -name "*.jpg" -not ( -name "DSC1011.jpg" -o -name "Dsc1015.jpg" -o -name "Dsc1020.jpg" ) -print
```
If the output looks good, you can switch `-print` to `-delete` to remove them right away. Just make sure to double-check that you're excluding the right files!
Thanks for the tip! I really want to get this right!
For one-off tasks, I'd actually suggest handling it a bit differently. Move the files you want to keep to a separate directory and then delete everything else. You can do something like:
```bash
mkdir save
mv DSC1011.jpg Dsc1015.jpg Dsc1020.jpg save/
rm *
mv save/* .
rmdir save
```
It's a safer method and avoids mistakes with deleting files.
That sounds really practical. I'll remember that idea!
Just a reminder, using `rm -i` can be risky because you might accidentally hit 'y' to confirm deletes you didn't intend. Using `find` with `xargs` can be safer too. Just be mindful of spaces in filenames, though!
Thanks for the warning! I’ll definitely practice careful deletion.
Awesome, I'm definitely adding this to my bash cheatsheet!