Edit each line in a file in Ruby

后端 未结 5 974
隐瞒了意图╮
隐瞒了意图╮ 2020-12-14 02:52

I\'m trying to find a simple way of editing each line in a file, and I\'m having some trouble understanding how to use the File class to do so.

The file

5条回答
  •  臣服心动
    2020-12-14 03:42

    The problem with the accepted answer is that it modifies file permissions and ownership (pay attention to that).

    Another approach is to use inplace editing inside Ruby (not from the command line):

    #!/usr/bin/ruby
    
    def inplace_edit(file, bak, &block)
        old_stdout = $stdout
        argf = ARGF.clone
    
        argf.argv.replace [file]
        argf.inplace_mode = bak
        argf.each_line do |line|
            yield line
        end
        argf.close
    
        $stdout = old_stdout
    end
    
    inplace_edit 'test.txt', '.bak' do |line|
        line = line.gsub(/search1/,"replace1")
        line = line.gsub(/search2/,"replace2")
        print line unless line.match(/something/)
    end
    

    If you don't want to create a backup then change '.bak' to ''.

提交回复
热议问题