How Can I Delete All But a Few Files in a Directory?

0
7
Asked By CuriousCoder92 On

Hey everyone! I'm new to Linux and bash, and I need some help. I want to delete an entire directory filled with mp3 files, but I want to keep 1-2 specific files. The catch is that these files have similar names but differ by just a few digits, which makes it tricky for me. How can I delete everything except those few files without moving them out of the directory?

4 Answers

Answered By SwiftSteve On

You could also use a file manager like Midnight Commander (mc) for this task. It gives you a visual interface to manage files, making it a bit easier if you're not yet familiar with the terminal.

Answered By TechWhiz88 On

You can use extended globs for this! First, enable the extended glob option by running `shopt -s extglob`. After that, you can do a dry run with `ls !(file_to_keep1.mp3|file_to_keep2.mp3)` to see what will be deleted. If that looks good, swap `ls` for `rm` and it will delete everything except the files you want to keep.

Answered By SimpleSolutions22 On

Here's a simpler approach: move the files you want to keep to a different location temporarily, delete everything else, and then move your files back. It minimizes any risks and is a lot easier if you're not comfortable with the command line.

Answered By FileFinderPro On

Try this command: `find . -type f ! -name 'file1.mp3' ! -name 'file2.mp3' -delete`. This command finds all files in the current directory, excludes the two you want to keep, and deletes everything else. I recommend running it without the `-delete` option first to double-check it's picking the right files.

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.