Gsub case insensitive with a twist

I have a folder with files with names of users in the filename.
I want to remove the user’s name from the file names.

Simplified a bit, the code is:

usernames = Array.new
usernames << “David”
usernames << “Tom”
usernames << “Amy”
usernames << “Fred”

path = “C:\files”
Dir.chdir(path)

Dir.foreach(path) do |filename|
if File.file?(filename) then
newName = filename
usernames.each do |uname|
newName= newName.gsub(uname, ‘xx’)
end
end
if filename != newName then
File.rename(filename, newName)
end
end

This works. When new users join, i add to the name to usernames Array.

The issue is the case of the usernames in the filename. Sometimes the
filename is AMY.timesheet.xls, while other times it could be
aMy.timesheet.xls.

How do i modify this line so that the case is ignored?
newName= newName.gsub(uname, ‘xx’)

I found a page that uses “/(what)/i” where my uname is. I tried various
variation of /#{uname}/, with and without quotes, but i keep getting
“empty range in char class”

Any ideas?

Thanks

Nimara Aramin wrote in post #1142135:

I have a folder with files with names of users in the filename.
I want to remove the user’s name from the file names.

Simplified a bit, the code is:

usernames = Array.new
usernames << “David”
usernames << “Tom”
usernames << “Amy”
usernames << “Fred”

This can be simplified to

usernames = %w{
David
Tom
Amy
Fred
}

path = “C:\files”
Dir.chdir(path)

It’s usually a bad idea to use this. Better not do this as relative
paths which are passed via command line will break.

Dir.foreach(path) do |filename|
if File.file?(filename) then
newName = filename
usernames.each do |uname|
newName= newName.gsub(uname, ‘xx’)
end
end
if filename != newName then
File.rename(filename, newName)
end
end

You can simplify that as well

REPL = ‘xx’.freeze

rx = /\b(?:#{Regexp.union *usernames})\b/i

Dir["#{path}/*"].each do |f|
fnew = f.gsub rx, REPL
File.rename f, fnew unless f == fnew
end

This works. When new users join, i add to the name to usernames Array.

The issue is the case of the usernames in the filename. Sometimes the
filename is AMY.timesheet.xls, while other times it could be
aMy.timesheet.xls.

How do i modify this line so that the case is ignored?
newName= newName.gsub(uname, ‘xx’)

In the code above I use /i to make the regex case insensitive.

I found a page that uses “/(what)/i” where my uname is. I tried various
variation of /#{uname}/, with and without quotes, but i keep getting
“empty range in char class”

Any ideas?

See above.

Cheers

robert

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs