11

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.

0

6 Answers 6

31

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

1
  • Never knew about the second arg to File.basename. So much cleaner than some nasty thing like File.basename(f).sub(/\.[^.]+$/, '') that I've always done before. Commented Jan 15, 2016 at 3:48
12

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
1
  • 1
    That is great for rails app, since you use rake by default anyway Commented Feb 12, 2021 at 17:42
7

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
3

Simpler

'abc . . def.mp3'.sub /\.[^\.]+$/, '.opus'
1
  • should be \.[^\.]+$ (escaping the first dot) :) Commented Oct 4, 2017 at 18:37
2

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
1
  • 2
    I had to use f.basename(f.extname), otherwise basename includes extension.
    – sites
    Commented Oct 4, 2013 at 21:17
0

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.

  1. dir = "path/to/remote/directory"
  2. actual_ext = ".eml"
  3. desired_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

Not the answer you're looking for? Browse other questions tagged or ask your own question.