Prepend a single line to file with Ruby

后端 未结 8 664
再見小時候
再見小時候 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:13

    fwiw this seems to work:

    #!usr/bin/ruby
    
    f = File.open("myfile", "r+")
    lines = f.readlines
    f.close
    
    lines = ["something\n"] + lines
    
    output = File.new("myfile", "w")
    lines.each { |line| output.write line }
    output.close
    

提交回复
热议问题