ruby - delete all files with names matching a pattern

Matthieu Raynaud de Fitte picture Matthieu Raynaud de Fitte · Aug 15, 2016 · Viewed 7.8k times · Source

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

Answer

orde picture orde · Aug 15, 2016

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)}