How do I delete folders using regex from Linux terminal
Asked Answered
R

3

10

Say I have folders:

img1/
img2/

How do I delete those folders using regex from Linux terminal, that matches everything starts with img?

Ruthy answered 12/8, 2012 at 19:7 Comment(1)
For the record, the shell's glob wildcard expressions are not proper regular expressions.Hatchel
P
31

Use find to filter directories

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

As it was mentioned in a comments this is using shell globs not regexs. If you want regex

$ find . -type d -regex "\./img.*" -exec rm -rf {} \;
Pariah answered 12/8, 2012 at 19:31 Comment(5)
one way to improve this could consist in adding -maxdepth 1 to find like that find . -type d -maxdepth 1 -regex "\./img.*" -exec rm -rf {} \; it will be faster.Substantial
I used your command quite a lot to clean the old backups on our production servers, but I can't figure out a regex to get all folders except the first of the month (means I want to wipe out every backup folder except 1 for each month). The folders name are defined like this: "yyyy.mm.dd.hh.MM.ss" (ex: 2016.07.29.03.00.19). Even find . -type d -regex "\./2016\.*" does not return anything ... any idea?Bolection
try find . -type d -regex ".*/2016.*"Pariah
{} is replaced by the file name and \; marks the end of the command passed to exec (if you don't escape it it would be taken by the shell)Pariah
Other discussions also mention $ find . -type d -regex "^\./img.*$" -exec rm -rf {} +Perigynous
A
20

you could use

rm -r img*

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

EDIT:

to remove only directories in the current working directory starting with img

rm -r img*/
Awildaawkward answered 12/8, 2012 at 19:11 Comment(4)
this will also delete any file that will match the expression, this command delete everything that match the expression, not only directories.Substantial
the OP says 'that matches everything starts with img?'Awildaawkward
If name must start img you should use ^img.*. Without ^ character name may have img for example on the middle.Proponent
as my solution was not using full regex just shell glob wildcard, as mentioned in other comment, that doesnt happen in this caseAwildaawkward
P
2

In the process of looking for how to use regexps to delete specific files inside a directory I stumbled across this post and another one by Mahmoud Mustafa: http://mah.moud.info/delete-files-or-directories-linux

This code will delete anything including four consecutive digits in 0-9, in my case folders with months and dates ranging from Jan2002 - Jan2014:

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

Hope that helps anyone out there looking around for how to delete individual files instead of folders.

Planchette answered 7/4, 2014 at 17:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.