搜索文件和替换时遇到问题

时间:2018-08-13 12:37:48

标签: ruby

我在搜索文件和编辑文件的某些参数时遇到了一些麻烦。代码在下面

do

所以现在它的作用是将文件内容打印两次,我只能假设它是因为它在textToReplace循环中。我的最终目标是文件具有textToReplace2Primefaces 6.0,我需要它来通读文件,用用户输入的内容替换并保存/写入对文件的更改。

2 个答案:

答案 0 :(得分:2)

  

它将文件内容打印两次,我只能假设它是因为它在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        

答案 1 :(得分:1)

您将需要重复使用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

OR

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