T145
T145

Reputation: 69

How do I rename the extension of an individual file through Ruby?

I'm trying to figure out an efficient way of renaming a single file's extension. I've looked into a bunch of methods online, but all of them seem to be for converting files in bulk, using basic .each do blocks. In those blocks, I noticed FileUtils was used a lot, but I supposed it was because that a directory path was given that its usage was imminent. I know how to do the bulk method, I'm just not sure about an individual method, w/ something along the lines of: def convert_file_extension(input_file) ... end

Any help is greatly appreciated!

Upvotes: 0

Views: 740

Answers (3)

user1934428
user1934428

Reputation: 22217

Adding to the solutions given above:

You can take apart a file path into the individual components: File.dirname yields the directory part, File.extname returns the extension. File.basename gives you just the filename, optionally with extension removed. In this way, you can also easily construct the new file name (and, of course, use then File.rename to actually change the filename).

Upvotes: 0

T145
T145

Reputation: 69

This statement does the trick:

def self.rename_file(input_file, output_file)
  File.rename(input_file, output_file) if !File.exist?(output_file)
end

Thanks to @7stud & @ostapische!

Upvotes: 1

7stud
7stud

Reputation: 48599

def change_ext(fname, new_ext)
  i = fname.rindex(".") 
  i ? (fname[0...i] + new_ext) : (fname + new_ext)
end

puts change_ext("/usr/local/file", ".xyz")
puts change_ext("/usr/local/file.txt", ".xyz")


--output:--
/usr/local/file.xyz
/usr/local/file.xyz

Upvotes: 0

Related Questions