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

前端 未结 5 826
傲寒
傲寒 2021-02-05 14:39

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

5条回答
  •  孤独总比滥情好
    2021-02-05 15:03

    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 {} \;
    

提交回复
热议问题