Read, edit, and write a text file line-wise using Ruby

后端 未结 4 613
长情又很酷
长情又很酷 2020-12-02 11:06

Is there a good way to read, edit, and write files in place in Ruby?

In my online search I\'ve found stuff suggesting to read it all into an array, modify said array

4条回答
  •  天涯浪人
    2020-12-02 11:32

    If you want to overwrite a file line by line, you'll have to ensure the new line has the same length as the original line. If the new line is longer, part of it will be written over the next line. If the new line is shorter, the remainder of the old line just stays where it is. The tempfile solution is really much safer. But if you're willing to take a risk:

    File.open('test.txt', 'r+') do |f|   
        old_pos = 0
        f.each do |line|
            f.pos = old_pos   # this is the 'rewind'
            f.print line.gsub('2010', '2011')
            old_pos = f.pos
        end
    end
    

    If the line size does change, this is a possibility:

    File.open('test.txt', 'r+') do |f|   
        out = ""
        f.each do |line|
            out << line.gsub(/myregex/, 'blah') 
        end
        f.pos = 0                     
        f.print out
        f.truncate(f.pos)             
    end
    

提交回复
热议问题