To remove all files and directories in a directory except for two specific folders using the Linux command line, you can use the find command or a combination of ls and rm with careful filtering. Below are a few methods to achieve this:
Method 1: Using find
The find command is a powerful tool for this task. You can use it to locate all files and directories except the ones you want to keep, and then delete them.
You can list all items in the directory, filter out the folders you want to keep, and then delete the rest. This method is more manual and should be used with caution.
bash
ls -A /path/to/directory | grep -v -E '^(folder1|folder2)$' | xargs -I {} rm -rf /path/to/directory/{}
ls -A: Lists all files and directories (including hidden ones) except . and ...
grep -v -E '^(folder1|folder2)$': Excludes folder1 and folder2 from the list.
xargs -I {} rm -rf /path/to/directory/{}: Passes the filtered list to rm -rf for deletion.
Example:
To keep docs and logs in /home/user/data:
bash
ls -A /home/user/data | grep -v -E '^(docs|logs)$' | xargs -I {} rm -rf /home/user/data/{}
Method 3: Using shopt and Extended Globbing
If you're using Bash, you can enable extended globbing to exclude specific folders and delete the rest.