Recursively Delete all files with names matching a Regular Expression

Logical Progression of building a command line trick

So lets take this step by step…

First list all the files

Lets get a recursive list of all files in the current directory…

1
2
$ find .
...LOTS of files...

Find filenames by Regex

Ok, that’s a big list, but I only need certain files.

1
2
3
4
$ find . | grep \.bak[0-9]*\.txt
test.bak.txt
test.bak1.txt
...etc

Use sed to alter the list a bit

So for each row, were adding quoting it, and adding rm to the beginning. This will just output the list of commands, it won’t actually remove the files. MAKE SURE YOU DO THIS FIRST and you like the list it creates. Or don’t blame me if you delete everything on your whole computer.

1
2
3
4
find . | grep \.bak[0-9]*\.txt | sed -E 's/(.*)/rm "\1"/'
rm "test.bak.txt"
rm "test.bak1.txt"
...etc

Now we get dangerous

You could just copy and paste that list into the terminal. Or you could be really cool and just pipe it to bash…
BUT LIKE I SAID ABOVE, RUN THE LIST FIRST AND MAKE SURE YOU LIKE THE RESULTS BEFORE YOU PULL THE TRIGGER.

1
find . | grep \.bak[0-9]*\.txt | sed -E 's/(.*)/rm "\1"/' | bash
Category(s): find, grep, sed
Tags: ,

3 Responses to Recursively Delete all files with names matching a Regular Expression

  1. Wow really good information

  2. Thank you so much. Been trying to accomplish this for hours.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

 

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Spam protection by WP Captcha-Free