Rename files using regex

I have 3 files named test.out, test2.out, test3.out
how can I rename them at once to text{2…3}.out using “File.rename” and regex?

Hi masoud,

You can use the Dir.glob with File.rename to rename your files. Here is an example:

Dir.glob('test*.out').each do |file|
  new_name = file.sub(/test(\d*)\.out/, 'text\1.out')
  File.rename(file, new_name)
end

This code will match all files starting with ‘test’ and ending with ‘.out’, then rename them using the regex pattern. Happy coding!