Reputation: 61
In directory C:\Users\Scripts
, I have files named:
2A_Apple_VC_20180101.txt
2A_Apple_VC_20180201.txt
2A_Apple_VC_20180301.txt
etc.
How can I insert the phrase Vendor
right after 2A_
for all the filenames in that directory that starts with 2A_
, permanently changing the filenames to:
2A_Vendor_Apple_VC_20180101.txt
2A_Vendor_Apple_VC_20180201.txt
2A_Vendor_Apple_VC_20180301.txt
Upvotes: 2
Views: 62
Reputation: 61
Reworked version using Max's response:
#!/usr/bin/env ruby
require 'rubygems'
paths = Dir.glob("C:\Users\Scripts/*.txt")
paths.each do |path|
puts "File #{path}"
if path =~ /2A_/
puts "Find 2A"
new_path = path.sub(/2A_/, "2A_Vendor_")
puts "New file: #{new_path}"
File.rename path, new_path
end
end
Upvotes: 1
Reputation: 26768
You can get a list of the file paths in the directory with Dir.glob:
paths = Dir.glob("C:\Users\Scripts/*.txt")
Then rename using String#sub and FileUtils.mv or File.rename:
paths.each do |path|
if path =~ /^2A_/
new_path = path.sub /^2A_/, "2A_Vendor_"
File.rename path, new_path
end
end
Upvotes: 1
Reputation: 2052
You can try File#rename
Dir["2A_*.txt"].each do |f|
File.rename(f, f.sub('2A_', '2A_Vendor_'))
end
Or with path
path = 'your_path_here'
Dir.glob("#{path}/2A_*.txt").each do |f|
File.rename(f, f.sub('2A_', '2A_Vendor_'))
end
For Windows you probably need to do with backslashes this this
Upvotes: 1