Change file extension with ruby

I have a list of .eml files that are in a remote folder, they say

\\abcremote\pickup 

I want to rename all files from

 xyz.eml to xyz.html 

Could you guys help me do this with ruby.

Thanks in advance.

+8
ruby ruby-on-rails rubygems
source share
5 answers

Improve the previous answer a bit:

 require 'fileutils' Dir.glob('/path_to_file_directory/*.eml').each do |f| FileUtils.mv f, "#{File.dirname(f)}/#{File.basename(f,'.*')}.html" end 

File.basename(f,'.*') give you a name without an extension, otherwise the files will have a filename .eml.html instead of file_name.html

+22
source share

Rake offers a simple command to change the extension:

 require 'rake' p 'xyz.eml'.ext('html') # -> xyz.html 

Improve the previous answers a bit:

 require 'rake' require 'fileutil' Dir.glob('/path_to_file_directory/*.eml').each do |filename| FileUtils.mv( filename, filename.ext("html")) end 
+7
source share

while you have access to this folder, you should use Dir.glob and FileUtils.mv

 Pathname.glob('path/to/directory/*.eml').each do |f| FileUtils.mv f, "#{f.dirname}/#{f.basename}.html" end 
+2
source share

Simpler

 'abc . . def.mp3'.sub /.[^\.]+$/, '.opus' 
+2
source share

One way to do this is to use the net-sftp library: In the method below, all files with the required file extension will be renamed, which will also not be affected by other formats.

  • dir = "path / to / remote / directory"
  • actual_ext = ".eml"
  • wish_ext = ".html"

 require 'net/sftp' def add_file_extension(dir, actual_ext, desired_ext) Net::SFTP.start(@host, @username, @password) do |sftp| sftp.dir.foreach(dir) do |file| if file.name.include? actual_ext sftp.rename("#{dir}/#{file.name}", "#{dir}/#{file.name.slice! actual_ext}#{desired_ext}") else raise "I cannot rename files other than which are in #{actual_ext} format" end end end end 
0
source share

All Articles