Ruby用于替换两个标记之间的文件内容

时间:2015-03-18 09:55:46

标签: ruby

尝试像Replace content in a file between two markers那样做,但接受的答案似乎没有效果:

的index.html

<!--start-->Hello world<!--end-->

myscript.rb

def replace(file_path, contents)
    file = File.open(file_path, "r+")
    html = ""

    while(!file.eof?)
        html += file.readline
    end

    file.close()

    return html.gsub(/<!--start-->(.*)<!--end-->/im, contents)
end

thing = ["Foo", "Bar", "Baz"].sample

replace("/path/to/index.html", thing)

运行ruby myscript.rb后,index.html保持不变。我在Ruby 2.2.0上。

1 个答案:

答案 0 :(得分:2)

尝试更改脚本,如下所示:

def replace(file_path, contents)
  content = File.read(file_path)
  new_content = content.gsub(/(<!--start-->)(.*)(<!--end-->)/im, "\\1#{contents}\\3")

  File.open(file_path, "w+") { |file| file.puts new_content }
  new_content
end

thing = ["Foo", "Bar", "Baz"].sample

replace("./my_file", thing)

使用文件时 - 请检查此great tutorial

祝你好运!