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
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:
ls -1 | grep -v 'name_of_file_to_keep.txt' | xargs rm -f
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:
ls -1 | grep -E -v 'not_file1.txt|not_file2.txt' | xargs rm -f
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:
find . -maxdepth 1 -type f -not -name "*.txt" -exec rm -f {} \;