Prepend a single line to file with Ruby

后端 未结 8 662
再見小時候
再見小時候 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
        }`
    
    0 讨论(0)
  • 2020-12-14 20:26

    I have came up with something like this, it is a little bit more descriptive and less cryptic than other solutions I've seen:

    def file_prepend(file, str)
      new_contents = ""
      File.open(file, 'r') do |fd|
        contents = fd.read
        new_contents = str << contents
      end
      # Overwrite file but now with prepended string on it
      File.open(file, 'w') do |fd| 
        fd.write(new_contents)
      end
    end
    

    And you can use it like this:

    file_prepend("target_file.txt", "hello world!\n")
    
    0 讨论(0)
提交回复
热议问题