How to delete folders using regex from a Linux terminal

Let's say I have folders:

img1/
img2/

How to delete these folders using regex from a Linux terminal that matches all starts with img?

+5
source share
3 answers

Use search to filter directories

$ find . -type d -name "img*" -exec rm -rf {} \;

As mentioned in the comments, this is using shell globs not regular expressions. If you want regex

$ find . -type d -regex "\./img.*" -exec rm -rf {} \;
+13
source

you can use

rm -r img*

which should delete all files and directories in the current working directory, starting with img

EDIT:

delete only directories in the current working directory, starting with img

rm -r img*/
+10
source

, , , - : http://mah.moud.info/delete-files-or-directories-linux

This code will delete everything, including four consecutive digits in 0-9, in folders with a couple of months and dates in the range from January 2002 to January 2010:

rm -fr `ls | grep -E [0-9]{4}`

Hope someone out there looked around how to delete individual files instead of folders.

0
source

All Articles