Sunday, September 18, 2016

How to remove all files except one in unix using find

In some case you need to delete all files in current folder except for a file of interest. You can do this with find command by adding ! to specify that you don't want a match with a file of that particular name.


find . ! -name 'file.name' -type f -exec rm -f {} +

Check the contents of the folder:

DN52eik9:testttt milospjanic$ ls -ltrh
total 0
-rw-r--r--  1 milospjanic  staff     0B Sep 18 11:54 file.name
-rw-r--r--  1 milospjanic  staff     0B Sep 18 11:54 file2.name
-rw-r--r--  1 milospjanic  staff     0B Sep 18 11:54 file3.name
DN52eik9:testttt milospjanic$ find . ! -name 'file.name' -type f -exec rm -f {} +
DN52eik9:testttt milospjanic$ ls -ltrh
total 0
-rw-r--r--  1 milospjanic  staff     0B Sep 18 11:54 file.name

No comments:

Post a Comment