How can I delete all but a few specific JPG files in a directory?

0
1
Asked By CuriousCoder99 On

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

Answered By ShellScribe15 On

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.

LearningBash101 -

Awesome, I'm definitely adding this to my bash cheatsheet!

Answered By ScriptMaster42 On

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!

AmateurCoder66 -

Wow, that looks powerful! I'll have to try it out.

CodeFixer88 -

Just a heads-up: you can clean it up a bit and make it more readable by using `if` instead of `&&`.

Answered By FileMover73 On

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!

PlayfulLearner22 -

Thanks for the tip! I really want to get this right!

Answered By PragmaticUser01 On

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.

CautiousDave -

That sounds really practical. I'll remember that idea!

Answered By SafetyFirst99 On

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!

NervousNewbie44 -

Thanks for the warning! I’ll definitely practice careful deletion.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.