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.
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.
find supports a
-delete
option so you do not need to-exec
. You can also pass multiple sets of-not -name somefile -not -name otherfile
Use the
not
modifier to removefile(s)
orpattern(s)
you don't want to delete, you can modify the1
passed to-maxdepth
to specify how many sub directories deep you want to delete files fromYou can also do:
In bash, you can use:
In general, using an inverted pattern search with grep should do the job. As you didn't define any pattern, I'd just give you a general code example:
The
ls -1
lists one file per line, so that grep can search line by line.grep -v
is the inverted flag. So any pattern matched will NOT be deleted.For multiple files, you may use egrep:
Update after question was updated: I assume you are willing to delete all files except files in the current folder that do not end with
.txt
. So this should work too:From within the directory, list the files, filter out all not containing 'file-to-keep', and remove all files left on the list.
To avoid issues with spaces in filenames (remember to never use spaces in filenames), use
find
and-0
option.Or mixing both, use
grep
option-z
to manage the-print0
names fromfind