I need to remove all the files in the current directory except one file, say abc.txt. Is there any command to rm all the other files in the directory except abc.txt?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
If you’re after a succinct command, then with extended globbing in bash, you should be able to use:
There are however several caveats to this approach.
This will run
rmon all entries in the directory (apart from “abc.txt”) and this includes subdirectories. You will therefore end up with the “cannot remove directory” error if subdirs exist. If this is the case, usefindinstead:If
!(abc.txt)returns a very long list of files, you will potentially get the infamous “argument list too long” error. Again,findwould be the solution to this issue.rm !(abc.txt)will fail if the directory is empty or if abc.txt is the only file. Example:You can workaround this using nullglob, but it can often be cleaner to simply use
find. To illustrate, a possible workaround would be: