How to rename a file in Ruby?
What about simply:
File.rename(f, folder_path + "/" + filename.capitalize + File.extname(f))
How to mass rename files in ruby
Slightly modified version:
puts "Enter the file search query"
searchPattern = gets.strip
puts "Enter the target to replace"
target = gets.strip
puts "Enter the new target name"
newTarget = gets.strip
Dir.glob(searchPattern).sort.each do |entry|
if File.basename(entry, File.extname(entry)).include?(target)
newEntry = entry.gsub(target, newTarget)
File.rename( entry, newEntry )
puts "Rename from " + entry + " to " + newEntry
end
end
Key differences:
- Use
.strip
to remove the trailing newline that you get fromgets
. Otherwise, this newline character will mess up all of your match attempts. - Use the user-provided search pattern in the
glob
call instead of globbing for everything and then manually filtering it later. - Use
entry
(that is, the complete filename) in the calls togsub
andrename
instead oforigin
.origin
is really only useful for the.include?
test. Since it's a fragment of a filename, it can't be used withrename
. I removed theorigin
variable entirely to avoid the temptation to misuse it.
For your example folder structure, entering *.jpg
, a
, and b
for the three input prompts (respectively) should rename the files as you are expecting.
How to rename particular files in the folder for ruby
This is going to be trick, here I am using FileUtils.mv
method.
path = "/home/itsme/videos"
Dir.open(path).each do |p|
next if File.extname(p) != ".mp4"
filename = File.basename(p, File.extname(p))
newname = filename.upcase + File.extname(p)
FileUtils.mv("#{path}/#{p}", "#{path}/#{newname}")
end
To use FileUtils class method you have to include it by using require fileutils
Ruby: Rename all files within a user given directory from .txt to text
As I understand from Your code,
1) You were not calling rename
function
2) Your rename
function had unnecessary checking of newfile
, currentdir
- if You want execute from current dir, it will understand "." symbol and will do glob in current dir.
I've moved pathname != "q"
to outside of rename
because of rename must do renaming, nothing else.
So final code:
#!/usr/bin/ruby
#This program was written by me
require 'fileutils'
def rename(pathname)
if File.directory?(pathname.to_s)
puts "renaming files in path"+pathname.to_s
Dir.glob(File.dirname(pathname.to_s)+"/*.txt").each do |f|
FileUtils.mv f, "#{File.dirname(f)}/#{File.basename(f,'.*')}.text"
puts "#{File.basename} => #{File.basename(f,'.*')}.text"
end
else
puts "Invalid Path"
end
end
puts "what directory would you like to change? "
pathname = gets.chomp
if pathname != "q"
rename(pathname)
end
p.s. normal user will just call:
rename -S .txt .text /path/to/files/*.txt
or:
rename -S .txt .text ./*.txt
Ruby renaming file in directory deletes files
The only way your script can erase files is by erasing existing file with the same name... You can check if a file already exists like that:
puts Dir["**/*"].length
folder_path = Dir.pwd
filenames = Dir.glob("*.png")
filenames.each_with_index do |filename, index|
new_name= folder_path + "/#{index}" + File.extname(filename)
raise "#{new_name} already exists" if File.exists?(new_name)
File.rename(filename, new_name)
end
Related Topics
How to Check If a Resource Exists in an Aws S3Bucket
How to Test Order-Conscious Equality of Hashes
Why Does Single '=' Work in 'If' Statement
How to Convert This Ruby String into an Array
New Way of Creating Hashes in Ruby 2.2.0
Why Rails Can Use 'If' as Hash Key But Not in Ruby
Recursive Rails Nested Resources
Ruby#Index Method VS Binary Search
Which Global Variable Is for Last Expression
Iterate Through Array of Hashes in Ruby
Rvm and Gems, Bundle Show and Gem List
How to Efficiently Extract Repeated Elements in a Ruby Array
Why Is the Timezone Off in Delayed_Job
Ruby Open-Uri Can't Open Url (M1 MAC)
Ruby Facebook Graph API Appsecret_Proof
Undefined Method Error When Creating Delayed_Job Workers with Script/Delay_Job