簡體   English   中英

搜索文件和替換時遇到問題

[英]Having issues searching through file and replacing

我在搜索文件和編輯文件的某些參數時遇到了一些麻煩。 代碼如下

file_names = ["#{fileNameFromUser}"]

file_names.each do |file_name|
 text = File.read(file_name)
 replacedcontent = text.gsub(/textToReplace/, "#{ReplaceWithThis}")
 replacedcontent += text.gsub(/textToReplace2/, "#{ReplaceWithThis2}")

# To write changes to the file, use:
File.open(file_name, "w") {|file| file.puts replacedcontent}
end

所以現在它的作用是將文件內容打印兩次,我只能假設它是因為它在do循環中。 我的最終目標是文件具有textToReplacetextToReplace2 ,我需要它讀取文件,用用戶輸入的內容替換並保存/寫入對文件的更改。

它兩次打印文件的內容,我只能假設它是因為它在do循環中

不,這是因為您附加了兩次:

text = first_replacement_result
text += second_replacement_result

有兩種方法可以執行此操作:一種具有突變:

text.gsub!(...) # first replacement that changes `text`
text.gsub!(...) # second replacement that changes `text` again

或鏈式替換:

replacedcontent = text.gsub(...).gsub(...) # two replacements one after another        

您將需要重新使用replacedcontent而不是將其串聯起來以避免打印兩次。

file_names = ["#{fileNameFromUser}"]

file_names.each do |file_name|
text = File.read(file_name)
replacedcontent = text.gsub(/textToReplace/, "#{ReplaceWithThis}")
replacedcontent = replacedcontent.gsub(/textToReplace2/, "#{ReplaceWithThis2}")

# To write changes to the file, use:
File.open(file_name, "w") {|file| file.puts replacedcontent}
end

要么

replacedcontent = text.gsub(/textToReplace/, "#{ReplaceWithThis}").gsub(/textToReplace2/, "#{ReplaceWithThis2}")

暫無
暫無

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

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