Ruby - delete all files with names matching the pattern

I have several files (in a folder containing thousands of files), for example:

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

How to delete all page_code * files

Note. I do not want to use FileUtils or shell

+7
ruby delete-file
source share
2 answers

Dir::glob supports a one-character pattern (i.e. ? ). Based on your example, can you find the appropriate files in this directory with ? and then delete them.

 Dir.glob('/home/your_username/Documents/page_code?.txt').each { |file| File.delete(file)} 
+7
source share

To delete files using a wildcard.

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

The regular expression in the selection element is used to capture the required files.

+1
source share

All Articles