【问题标题】:Ruby to replace contents of file between two markersRuby替换两个标记之间的文件内容
【发布时间】:2015-03-18 18:44:32
【问题描述】:

尝试像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 上。

【问题讨论】:

    标签: ruby


    【解决方案1】:

    尝试如下更改脚本:

    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

    祝你好运!

    【讨论】:

    • 您的方法看起来好多了,但不幸的是索引文件保持不变。我错过了什么吗?
    • @FlyntHamlock - 你完全正确!我刚刚更新了我的答案! (加上一些更短的语法被使用)。为混淆道歉!
    • 太棒了-谢谢!有没有办法不删除&lt;!--start--&gt;&lt;!--end--&gt;
    • @FlyntHamlock - 当然可以!检查我的答案更新! (另外,看看这个answer)。祝你好运!
    • 绝对华丽!再次感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-14
    • 1970-01-01
    • 2017-02-25
    • 1970-01-01
    • 2019-06-24
    • 2012-09-21
    • 2020-10-30
    相关资源
    最近更新 更多