renaming files using variables in Ruby

只愿长相守 提交于 2019-12-25 05:10:34

问题


How do you use variables to rename files in Ruby?

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

The above example is fine when using irb, but I writing a script where both var1 and var2 are unknown to me.

for example:

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)

does not work... but if i use puts var1 I see the file name I want.

The error I get is:

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

but the file audio-0.aac is there... I'm looking at it.


I am certain I have located the problem: it seems to be adding a variable to another variable. This is a simplified example that produces the same output:

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)

OUTPUT :

/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:


You should be passing the full file path to File.rename, not just the basename

I am not sure what is going on in your example inside File.basename() , but imagine the following:

  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

So instead, you need to pass the full path to File.rename, like so:

  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)


来源:https://stackoverflow.com/questions/9042026/renaming-files-using-variables-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!