Prepend a single line to file with Ruby

后端 未结 8 688
再見小時候
再見小時候 2020-12-14 19:35

I\'d like to add a single line to the top a of file with Ruby like this:

# initial file contents
something
else

# file contents after prepending \"hello\" o         


        
8条回答
  •  孤街浪徒
    2020-12-14 20:21

    Pure, but works. Minimize file-related operations.

    `#!/bin/ruby
    inv_file = File.open("./1.txt","r+") { |f|
        #Read file string by-string
        until f.eof?
            #Searching for some
            if f.readline[/condition here/]
                #remember position
                offset = f.pos
                #Find it? - stop reading
                break
            end
        end
        #Remember what contains rest of file
        tail = f.readlines
        #Again to offset
        f.pos = offset
        #insert what necessary
        f.puts "INSERTED"
        #reconstruct tail
        f.write tail.join
        }`
    

提交回复
热议问题