2016-11-17 72 views
1

這裏的一些幫助將不勝感激。目標是將所有.txt文件重命名爲ruby中用戶輸入的目錄中的.text。我必須使用fileutils作爲要求。當我運行我的當前腳本時,我沒有收到任何錯誤。然而,沒有任何事情發生......我相信你們中的一個人可能可以幫我指出這個問題。Ruby:將給定目錄中的所有文件從.txt重命名爲文本

#!/usr/bin/ruby 
#This program was written by me 
puts 「what directory would you like to change? 「 
require 'fileutils' 
pathname = gets.chomp 
def rename(pathname) 
    currentdir = Dir.new('.') 
    newfile = FileTest.exists?(pathname.to_s) 
    if pathname != "q" 
     if newfile == "true" 
      require 'fileutils' 
        newfile.each do |f| 
        FileUtils.mv "#{File.dirname(f)}/#{File.basename(f, '.*')}.txt", "#{File.dirname(f)}/#{File.basename(f,'.*')}.text" 
        end 
     elsif currentdir 
      require 'fileutils' 
      (currentdir).each do |f| 
       FileUtils.mv "#{File.dirname(f)}/#{File.basename(f, '.*')}.txt", "#{File.dirname(f)}/#{File.basename(f,'.*')}.text" 
      end 
     else 
      puts "Invalid Path" 
     end 
    end 
end 

編輯:我想我現在知道這個問題,但不知道在哪裏把代碼。我需要cd到用戶輸入的目錄,這應該是我只能更改主目錄中的.txt文件的原因。

此問題與建議的意見不同,因爲要求是使用fileutils並讓用戶輸入他們想要編輯的目錄。此項查找文件名從任何地方,並且不使用文件實用程序

+0

的可能的複製[如何在質量紅寶石重命名文件(http://stackoverflow.com/questions/10758694/how-to- mass-rename-files-in-ruby) – Wes

+0

這可能是因爲你從來沒有真正調用過重命名方法嗎? – Rashmirathi

+0

雖然不盡相同。要求是使用fileutils並讓用戶輸入他們想要編輯的目錄。此條目從任何地方查找文件名並且不使用fileutils –

回答

0

當我從代碼理解,

1)你沒有打電話rename功能

2)你rename功能有不必要的檢查newfile,currentdir - 如果你想從當前目錄執行,它會理解「。」符號,並會在當前目錄中執行glob。



我搬到pathname != "q"rename因爲重命名之外必須做重命名,沒有別的。

所以最終代碼:

#!/usr/bin/ruby 
#This program was written by me 

require 'fileutils' 

def rename(pathname) 
    if File.directory?(pathname.to_s) 
    puts "renaming files in path"+pathname.to_s 
    Dir.glob(File.dirname(pathname.to_s)+"/*.txt").each do |f| 
     FileUtils.mv f, "#{File.dirname(f)}/#{File.basename(f,'.*')}.text" 
     puts "#{File.basename} => #{File.basename(f,'.*')}.text" 
    end 
    else 
    puts "Invalid Path" 
    end 
end 

puts "what directory would you like to change? " 
pathname = gets.chomp 

if pathname != "q" 
    rename(pathname) 
end 



附:普通用戶只要致電:

rename -S .txt .text /path/to/files/*.txt 

或:

rename -S .txt .text ./*.txt 
+0

遇到同樣的問題我幾乎開始使用。我運行腳本並沒有任何反應。雖然沒有錯誤。 但是,如果路徑無效,它會發出警報。它以前沒有這樣做過。 –

+0

您可以編寫如何調用腳本以及您作爲路徑傳遞的內容嗎? – num8er

+0

還要確保在路徑中有該擴展名的文件您定義了 – num8er

相關問題