How to rename a file in Ruby? - ruby

Here's my .rb file:
puts "Renaming files..."
folder_path = "/home/papuccino1/Desktop/Test"
Dir.glob(folder_path + "/*").sort.each do |f|
filename = File.basename(f, File.extname(f))
File.rename(f, filename.capitalize + File.extname(f))
end
puts "Renaming complete."
The files are moved from their initial directory to where the .rb file is located. I'd like to rename the files on the spot, without moving them.
Any suggestions on what to do?

What about simply:
File.rename(f, folder_path + "/" + filename.capitalize + File.extname(f))

Doesn't the folder_path have to be part of the filename?
puts "Renaming files..."
folder_path = "/home/papuccino1/Desktop/Test/"
Dir.glob(folder_path + "*").sort.each do |f|
filename = File.basename(f, File.extname(f))
File.rename(f, folder_path + filename.capitalize + File.extname(f))
end
puts "Renaming complete."
edit: it appears Mat is giving the same answer as I, only in a slightly different way.

If you're running in the same location as the file you want to change
File.rename("test.txt", "hope.txt")
Though honestly, I sometimes I don't see the point in using ruby at all...no need probably so long as your filenames are simply interpreted in the shell:
`mv test.txt hope.txt`

If you are on a linux file system you could try mv #{filename} newname
You can also use File.rename(old,new)

Don't use this pattern unless you are ready to put proper quoting around filenames:
`mv test.txt hope.txt`
Indeed, suppose instead of "hope.txt" you have a file called "foo the bar.txt", the result will not be what you expect.

Related

Changing filenames in Ruby when all files have no type?

I have a directory filled with 5 files with no filetype (perhaps their filetype is '.txt' - I am uncertain), named "file1", "file2"...
I am trying to convert them to CSV format with the following code:
require('fileutils')
folder_path = "correct_folder_path"
Dir.foreach(folder_path) do |f|
next if f == '.' || f == '..'
#confirm inputs are correct (they are)
#p f
#p f+".csv"
File.rename(f, f+".csv")
end
I have p'd out f to confirm everything is working, but the line
File.rename(f,f+".csv")
is throwing the error: "in `rename': No such file or directory... (Errno::ENOENT)"
Does anyone know why this isn't working?
With Dir and File
You could change the directory to folder_path. If some files might have '.txt' extension, you need to remove the extension first in order not to get a .txt.csv file :
folder_path = "correct_folder_path"
Dir.chdir(folder_path) do
Dir.foreach(".") do |f|
next if File.directory?(f)
basename = File.basename(f, '.*')
new_file = basename + '.csv'
p f
p new_file
## Uncomment when you're sure f and new_file are correct :
# File.rename(f, new_file) unless f == new_file
end
end
With Pathname
With Pathname, it's usually much easier to filter and rename files :
require 'pathname'
folder_path = "correct_folder_path"
Pathname.new(folder_path).children.each do |f|
next if f.directory?
p f
p f.sub_ext('.csv')
## Uncomment if you're sure f and subext are correct :
# f.rename(f.sub_ext('.csv'))
end
The paths returned by Dir.foreach are relative to the folder_path that you passed in. Your call to File.rename tries to rename a file in the current working directory, which is probably not the same directory as that specified by folder_path.
You can make the rename succeed by prepending folder_path to the filename:
f = File.join(folder_path, f)
File.rename(f, f + ".csv")
One alternative:
require 'pathname'
folder.children.each do |child|
# Other logic here
child.rename(child.dirname + (child.basename.to_s + '.csv'))
end

How to prevent overwriting when copying files

I'm writing a script to copy files from one directory to another. I can't figure out how to do it when the destination folder doesn't have a file with the same name as the file to paste. Ideally the user should be able to pick whether to skip or to overwrite. Here's my code:
require 'fileutils'
mydir = '/path_to_my_dir_here/*.{JPG,jpg}'
pic_names = Dir[mydir]
puts
print "Copying #{pic_names.length} pics:"
pic_number = 1
pic_names.each do |filename|
dest_folder = '/path_to_my_destination_folder/My_bg_pics'
FileUtils.cp(filename, dest_folder)
pic_number = pic_number + 1
end
Use the preserve option with Fileutils.cp

Rename all files in directory?

My task:
Write a program to rename files using regular expressions. This
program will take three command line arguments: the directory in which
to rename files, a regular expression that matches files to be
renamed, and a string to replace the regular expression match. The
primary use is to change file extensions, but it should be able to
handle replacing any portion of the file name.It should run as
follows:
./fixname.rb dir 'pattern' replacement
The program I have written is:
puts "Renaming files..."
folder_path = ARGV[0]
reg_exp = ARGV[1].to_regexp
Dir.glob(folder_path + "/*").sort.each do |f|
filename = File.basename(f, File.extname(f))
myString = String.new
myString = filename
filename = myString.gsub(reg_exp, ARGV[2])
#puts myString
File.rename(f, folder_path + "/" + filename + File.extname(f))
end
puts "Renaming complete."
The rename doesn't happen when I am using regexp, otherwise it is working. I'm getting:
error "`gsub': no implicit conversion of nil into String (TypeError)"
What you think is a regex is not, it's a String containing a regex pattern.
You need to convert that to a Regexp object. How to do that is left to you.

Rename method of Ruby; escaping colon

How do you escape a colon, when renaming files in Ruby?
I have following code (names is a hash with data already filled in):
new_filename = ""
counter = 0
Dir.glob(folder_path + "/*").each do |f|
numbering = names.index(names.values.sort[counter])
new_filename = numbering + " - " + names.values.sort[counter]
puts "New file name: " + new_filename
File.rename(f, folder_path + "/" + new_filename + File.extname(f))
counter += 1
end
puts "Renaming complete."
The output of new_filename is correct, e.g. "Foo - Bar: Foo.txt". When it renames the file, the file has following format: "Foo - Bar/ Foo.txt".
I tried escaping with the colon with a backslash, but doesn't seem to work, because my output then looks like this: "Foo - Bar/\ Foo.txt".
Is is possible to have a colon in a string for renaming files?
FYI - in NTFS a colon identifies a separate stream of the same file... "Foo Bar: Foo.txt" identifies file "Foo Bar", stream " Foo.txt". Reference "Alternate Data Streams" (currently http://support.microsoft.com/kb/105763). AFIK this feature is not really widely used, though I have seen it used to tag files with thrid-party data (I use it to store a file's sha1 for dupe identification under the stream *:sha1).

Recursively convert all folder and file names to lower-case or upper-case

I have a folder structure like follows.
-FOO
-BAG
Rose.TXT
-BAR
JaCk.txt
I need the following output.
-foo
-bag
rose.txt
-bar
jack.txt
I realize you want ruby code, but I present to you a one liner to run in your shell:
for i in `find * -depth`; do (mv $i `echo $i|tr [:upper:] [:lower:]`); done
as found here: http://ubuntuforums.org/showthread.php?t=244738
Run it once, and it should do the trick.
Update
Ruby Code:
Dir.glob("./**/*").each do |file|
File.rename(file, file.downcase) #or upcase if you want to convert to uppercase
end
Dir["**/*"].each {|f| File.rename(f, f.downcase)}
The accepted answer does not work: when it tries to convert a directory first and then a file in that directory.
Here is the code that does work:
Dir.glob("./**/*").sort{|x| x.size}.each do |name|
x = name.split('/')
newname = (x[0..-2] + [x[-1].downcase]).join('/')
File.rename(name, newname)
end
(it sorts the list by length, so the direcotry will be converted after the file in it)
Recursive directory listing :
http://www.mustap.com/rubyzone_post_162_recursive-directory-listing
Uppercase/lowercase conversion :
http://www.programmingforums.org/thread5455.html
Enjoy :)
If you want to rename your files recursively, you can use **/*
folder = "/home/prince"
Dir["#{folder}/**/*"].each {|file| File.rename(file, file.downcase)}
If you just want the file array output in lowercase
Dir["#{folder}/**/*"].map(&:downcase)
Just a bit of Find.find is all you need:
require 'find'
Find.find(directory) do |path|
if(path != '.' && path != '..')
File.rename(path, path.downcase)
end
end

Resources