搜索文件的行并用数组中的值替换变量并循环直到数组没有更多值

时间:2012-06-14 15:11:20

标签: ruby arrays substitution

我想我在这附近,但有一个关键的部分让我不知所措。

template.txt

  

我是@file
  需要的   替换word文件   与数组中的每个值

subvalues.txt

  

WORD1
  WORD2
  WORD3
  word4

所以我正在做的是打开一个文件以追加使用

filex = file.new ("outputfile.txt" "a")

然后用

打开包含模板数据的文​​件
data = file.open("template.txt")

然后我使用

将数据导入数组
array1 = File.readlines("subvalues.txt")

这就是我被卡住的地方。如何遍历数组,用@file中的file1替换数组中的第一个元素,将输出写入outputfile.txt,替换@file中的file1再次使用数组中的第二个元素,将输出附加到outputfile.txt,并继续,直到数组没有更多值。

我找到了类似的帖子,但没有任何与我正在做的事情相符。我已经尝试将这些想法调整到我想要做的事情中,但似乎我做了一些倒退而且我无法让它发挥作用。

2 个答案:

答案 0 :(得分:2)

template.txt:

I am a @file that needs the word file replaced with each value in an array  

subvalues.txt

word1
word2
word3
word4

代码:

data = File.open('template.txt', &:read)
array = File.read('subvalues.txt').split
File.open('outputfile.txt', 'a') do |file|
  array.each do |value|
    file.write(data.gsub('@file', value))
  end 
end

答案 1 :(得分:0)

嗯,如果你想要的话,那就是简单的hacky。

substitutions_array.each do |elt|
  big_file.sub('file', elt)
end

这可能不是最好的方式,但它应该适合你。 Sub只进行一次替换,因此您可以遍历阵列。

编辑:我想我误解了你的问题,如果是这样,请看上面的答案。