How to delete all files in a folder EXCEPT certain ones in BASH

Imagine you have a folder that has about 20 files that you need and like 100 files that you don’t. In this case, there is a very simple bash script that allows you to do that in a jiffy!

Here it is:

ls | grep -v "hobba.txt\|\|\|.xlsx" | xargs rm

This command does the following (in order):

  1. lists all files in the folder with “ls”
  2. grep -v means grep everything except the following
  3. The list of files – or globs – that it’s going to ignore, you have to separate each by pipe preceded with a backslash. It ignores 3 files and 1 glob:
    1. hobba.txt
    4. .xlsx (means anything with extension .xlsx)
  4. Finally it deletes them one by one through the xargs rm


Sources: Many which I unfortunately forgot to take note of, but they are mostly from Stackoverflow

About SoCRaT

Systems Engineer, OSS & Linux Geek
This entry was posted in Linux, Uncategorized and tagged , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s