Reputation: 411
I have a list of .eml files which are in a remote folder say
\\abcremote\pickup
I want to rename all the files from
xyz.eml to xyz.html
Could you guys help me do that using ruby.
Thanks in advance.
Upvotes: 11
Views: 15742
Reputation: 27855
Rake offers a simple command to change the extension:
require 'rake'
p 'xyz.eml'.ext('html') # -> xyz.html
Improving the previous answers again a little:
require 'rake'
require 'fileutils'
Dir.glob('/path_to_file_directory/*.eml').each do |filename|
FileUtils.mv( filename, filename.ext("html"))
end
Upvotes: 12
Reputation: 2598
Pathname has the sub_ext()
method to replace the extension, as well as glob()
and rename()
, allowing the accepted answer to be rewritten a little more compactly:
require 'pathname'
Pathname.glob('/path_to_file_directory/*.eml').each do |p|
p.rename p.sub_ext(".html")
end
Upvotes: 7
Reputation: 481
One way to do this is by using net-sftp library: The below method will rename all the files with desired file extension which will also make sure other formats are untouched.
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
Upvotes: 0
Reputation: 7338
Improving the previous answer a little:
require 'fileutils'
Dir.glob('/path_to_file_directory/*.eml').each do |f|
FileUtils.mv f, "#{File.dirname(f)}/#{File.basename(f,'.*')}.html"
end
The File.basename(f,'.*')
will give you the name without the extension otherwise the files will endup being file_name.eml.html instead of file_name.html
Upvotes: 31
Reputation: 29599
as long as you have access to that folder location, you should be able to use Dir.glob
and FileUtils.mv
Pathname.glob('path/to/directory/*.eml').each do |f|
FileUtils.mv f, "#{f.dirname}/#{f.basename}.html"
end
Upvotes: 2