簡體   English   中英

如何使用Ruby搜索和替換目錄中所有文件中的字符串?

[英]How to search and replace strings in all of the files in my directory using Ruby?

基本上這就是問題所在。 我試圖弄清楚如何將“卡片排序”一詞替換為“卡片排序”,因為兩個詞之間的空格弄亂了我擁有的另一個腳本。 我需要將新的字符串替換(CardSort)寫在文件上,並用空格替換以前的字符串。

我整天都在努力(關於編程:(),我真是個笨蛋,這是到目前為止我要提出的內容:

# Set the variables for find/replace
@original_string_or_regex = /Card Sort/
@replacement_string = "CardSort"

Dir.foreach("~/Desktop/macshapa_v2") do |file_name|
    next if file_name == '.' or file_name == '..'  # do work on real items
    text = File.read(file_name)
    replace = text.gsub!(@original_string_or_regex, @replacement_string)
    File.open(file_name, "w") { |file| file.puts replace }
end

我認為問題在於我尚未定義變量“ file_name”,但我不知道應將其定義為什么。 基本上,它只需要遍歷整個目錄並進行更改即可。

另外,如果一個文件夾中有多個文件夾和子目錄,那么如何使它們遍歷所有文件夾並應用更改,而不必一個個地遍歷每個文件夾? 感謝所有幫助人員,我真的很感激。

您不需要定義file_name就是塊的結果。 如果您覺得什么都沒發生,可能是因為您的表情什么也沒返回。 嘗試將puts file_name添加到塊中,您將看到找到的文件。 我的猜測是您的腳本沒有要迭代的文件,因為Dir.foreach無法與~/

# Set the variables for find/replace
# you can use regular variables here
original_string_or_regex = /Card Sort/
replacement_string = "CardSort"

# Dir.glob will take care of the recursivity for you
# do not use ~ but rather Dir.home
Dir.glob("#{Dir.home}/Desktop/macshapa_v2/*") do |file_name|
  text = File.read(file_name)
  replace = text.gsub!(original_string_or_regex, replacement_string)
  File.open(file_name, "w") { |file| file.puts replace }
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM