Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby - delete all files with names matching a pattern

Tags:

I have multiple files (in a folder containing thousands of files), ex:

...
page_bonus.txt
page_code1.txt
page_code2.txt
page_text1.txt
page_text2.txt
page_text3.txt
...

How do I delete all page_code* files?

Note: I do not wish to use FileUtils or shell

like image 645
Matthieu Raynaud de Fitte Avatar asked Aug 14 '16 22:08

Matthieu Raynaud de Fitte


2 Answers

Dir::glob supports a single character wildcard (i.e. ?). Based on your example, you could locate the appropriate files in a given directory using ? and then delete them.

Dir.glob('/home/your_username/Documents/page_code?.txt').each { |file| File.delete(file)}
like image 111
orde Avatar answered Sep 23 '22 06:09

orde


To delete files with a wildcard.

Dir.glob("/tmp/files/*").select{ |file| /MY STRING/.match file }.each { |file| File.delete(file)}

The regular expression within the select is used to grab the files you want.

like image 23
Ian Purton Avatar answered Sep 19 '22 06:09

Ian Purton