I have a folder contenting several folders and I hope to delete all of them but leave one selected, how could I do this with the command "rm "under Ubuntu12.04??


As by deleting files one can get into serious problems, I would recomend moving unwanted files to some folder before deleting them from the disk. Let's create folder wastebasket and place it in ~:

mkdir ~/wastebasket/

Then, let's cd to the folder, which requires cleaning, and move all files except one, named precious, to wastebasket:

cd mess/
ls -1 | grep -xv precious | xargs -i mv -i {} ~/wastebasket/

If everything went as expected, delete the wastebasket:

rm -rf wastebasket

If the file is in the current directory you can just do:

for file in *; do if [ $file != 'NAME_OF_YOUR_FILE' ]; then rm -r $file; fi; done

Warning: May cause loss of valuable data, not tested with files that have special characters, spaces, new lines, zero characters, names of american presidents.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.