Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Linux terminal, how to delete all files in a directory except one or two

In a Linux terminal, how to delete all files from a folder except one or two?

For example.

I have 100 image files in a directory and one .txt file. I want to delete all files except that .txt file.

like image 422
Bilal Avatar asked Feb 14 '14 12:02

Bilal


1 Answers

From within the directory, list the files, filter out all not containing 'file-to-keep', and remove all files left on the list.

ls | grep -v 'file-to-keep' | xargs rm

To avoid issues with spaces in filenames (remember to never use spaces in filenames), use find and -0 option.

find 'path' -maxdepth 1 -not -name 'file-to-keep' -print0 | xargs -0 rm

Or mixing both, use grep option -z to manage the -print0 names from find

like image 83
Didier Trosset Avatar answered Oct 14 '22 09:10

Didier Trosset