Thursday, March 19, 2015

Remove all files in a directory except one or two

In Linux, have you ever wondered what is the command to execute in terminal to delete all files in a directory except one or two ? Its,

 find ! -name 'file.txt' -type f -exec rm -f {} +  
 
This command will remove all files except file.txt.

To remove directory, change type -f to type -d and add -r option to rm as below.

 find ! -name 'file.txt' -type d-exec rm -rf {} +  

Please becareful before executing command. If you accidentally type in an important folder, you may loose all contents.

Always try to understand to learn about each term before executing it :).

No comments:

Post a Comment