使用Ruby中的变量重命名文件

时间:2012-01-28 00:55:09

标签: ruby variables renaming

如何使用变量重命名Ruby中的文件?

File.rename("text1.txt", "text2.txt")

上面的例子在使用irb时很好,但是我编写了一个脚本,其中var1和var2都不为我所知。

例如:

script_dir = File.expand_path File.dirname(__FILE__)
Dir.chdir(script_dir)

Dir.glob('Cancer1-1.pencast').each do |pencast| 
pencast_title = File.basename(File.basename(pencast), '.*')
i = 1
audio_title = File.basename(`unzip -l #{pencast} | grep .aac | awk '{print $4;}' | awk 'NR=='#{i}''`)   
audio_path = `unzip -l #{pencast} | grep .aac | awk '{print $4;}' | awk 'NR=='#{i}''`
audio_extension = File.extname(File.basename(audio_path))
new_name = "#{pencast_title}-#{i}#{audio_extension}"
File.rename(audio_title, new_name)

不起作用...... 但如果我使用puts var1,我会看到我想要的文件名。

我得到的错误是:

prog_test.rb:12:in `rename': No such file or directory - audio-0.aac (Errno::ENOENT)
 or Cancer1-1-1.aac
    from prog_test.rb:12
    from prog_test.rb:5:in `each'
    from prog_test.rb:5

但文件audio-0.aac就在那里......我正在看它。


我确信我找到了问题: 它似乎是在另一个变量中添加一个变量。这是一个产生相同输出的简化示例:

audio_title = "audio-0.aac"
fullPath = File::SEPARATOR + "Users" + File::SEPARATOR + "name" + File::SEPARATOR + "Desktop" + File::SEPARATOR + audio_title
newname = File::SEPARATOR + "Users" + File::SEPARATOR + "name" + File::SEPARATOR + "Desktop" + File::SEPARATOR + "audio1.aac"

puts fullPath
puts newname

File.rename(fullPath, newname)

输出:

/Users/name/Desktop/audio-0.aac
/Users/name/Desktop/audio1.aac
prog_test.rb:22:in `rename': No such file or directory - /Users/name/Desktop/audio-0.aac or /Users/name/Desktop/audio1.aac (Errno::ENOENT)
    from prog_test.rb:22

1 个答案:

答案 0 :(得分:1)

您应该将完整文件路径传递给File.rename,而不仅仅是基本名称

我不确定File.basename()中你的例子中发生了什么,但想象如下:

  fullPath = "C:" + File::SEPARATOR + "Folder" + File::SEPARATOR + "File.txt" # C:\Folder\File.txt
  basename = File.basename(fullPath) # File
  newFileName = "File.bak"

  File.rename(basename, newFileName)
  # How can Ruby possibly know which directory to find the above file in, or where to put it? - It will just look in the current working directory

因此,您需要将完整路径传递给File.rename,如下所示:

  fullPath = "C:" + File::SEPARATOR + "Folder" + File::SEPARATOR + "File.txt" # C:\Folder\File.txt
  directory = File.dirname(fullPath) # C:\Folder
  newFileName = "File.bak"

  File.rename(fullPath, directory + File::SEPARATOR + newFileName)