如何使用變量在Ruby中重命名文件?使用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)
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
爲什麼選擇了倒票? – beoliver 2012-01-28 01:22:37