68

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?

  • In what way are they moved and not just renamed? Are they physically moved in the memory, you mean? What makes you believe that? Please elaborate why the current code is not satisfactory. – Gustav Larsson Apr 03 '11 at 15:35

5 Answers5

108

What about simply:

File.rename(f, folder_path + "/" + filename.capitalize + File.extname(f))
Mat
  • 202,337
  • 40
  • 393
  • 406
29

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.

Preacher
  • 2,410
  • 1
  • 19
  • 29
23

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`
boulder_ruby
  • 38,457
  • 9
  • 79
  • 100
  • This looks interesting. I'd love to see some explanation of how this works. – superluminary Feb 06 '13 at 12:16
  • 1
    Well, @superluminary, 6 years later, this works because the present working directory (`Dir.pwd` in irb or `pwd` in the shell) is the same as the files in the question. To determine if said files are in your directory, use `Dir.glob("*")` in irb or `ls` in shell. If your file is there, this stuff should work... – boulder_ruby Jun 13 '19 at 03:18
  • @User16119012 back in 2013, were you running Windows? – boulder_ruby Jun 13 '19 at 03:19
  • @User16119012 I was not --- was and still am running OSX – boulder_ruby Feb 28 '20 at 19:33
1

If you are on a linux file system you could try mv #{filename} newname

You can also use File.rename(old,new)

Steve
  • 21,163
  • 21
  • 69
  • 92
  • 1
    I'd rather not use Terminal commands and just use Ruby. This script is meant to run on Windows and Linux. Just a little helper script I'm writing to learn about Ruby. –  Apr 03 '11 at 15:29
0

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.

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Nicola Mingotti
  • 860
  • 6
  • 15