Tuesday 6 March 2018

rm - How to delete all but one file in Unix?




Possible Duplicate:
How to delete all files in a directory except some?



How to delete all but one(or some) file in Unix?


Something like


 rm -rf -ignore myfile.txt *

Answer



ls * | grep -v dont_delete_this_file | xargs rm -rf 

Example :


mkdir test && cd test
touch test1
touch test2
touch test3
touch test4
touch test5

To remove all files except 'test2' :


ls * | grep -v test2 | xargs rm -rf

Then 'ls' output is :


test2

EDIT:


Thanks for the comment. If the directory contains some files with spaces :


mkdir test && cd test
touch "test 1"
touch "test 2"
touch "test 3"
touch "test 4"
touch "test 5"

You can use (with bash) :


rm !("test 1"|"test 4")

'ls' output :


test 1
test 4

No comments:

Post a Comment

Where does Skype save my contact's avatars in Linux?

I'm using Skype on Linux. Where can I find images cached by skype of my contact's avatars? Answer I wanted to get those Skype avat...