Search code examples
rubyfileread-write

Delete first two lines and add two lines to file


I have a text file that starts with:

Title

aaa
bbb
ccc

I don't know what the line would include, but I know that the structure of the file will be Title, then an empty line, then the actual lines. I want to modify it to:

New Title

fff
aaa
bbb
ccc

I had this in mind:

lineArray = File.readlines(destinationFile).drop(2)
lineArray.insert(0, 'fff\n')
lineArray.insert(0, '\n')
lineArray.insert(0, 'new Title\n')
File.writelines(destinationFile, lineArray)

but writelines doesn't exist.

`writelines' for File:Class (NoMethodError)

Is there a way to delete the first two lines of the file an add three new lines?


Solution

  • I'd start with something like this:

    NEWLINES = {
      0 => "New Title",
      1 => "\nfff"
    }
    
    File.open('test.txt.new', 'w') do |fo|
      File.foreach('test.txt').with_index do |li, ln|
        fo.puts (NEWLINES[ln] || li)
      end
    end
    

    Here's the contents of test.txt.new after running:

    New Title
    
    fff
    aaa
    bbb
    ccc
    

    The idea is to provide a list of replacement lines in the NEWLINES hash. As each line is read from the original file the line number is checked in the hash, and if the line exists then the corresponding value is used, otherwise the original line is used.

    If you want to read the entire file then substitute, it reduces the code a little, but the code will have scalability issues:

    NEWLINES = [
      "New Title",
      "",
      "fff"
    ]
    
    file = File.readlines('test.txt')
    File.open('test.txt.new', 'w') do |fo|
      fo.puts NEWLINES
      fo.puts file[(NEWLINES.size - 1) .. -1]
    end
    

    It's not very smart but it'll work for simple replacements.

    If you really want to do it right, learn how diff works, create a diff file, then let it do the heavy lifting, as it's designed for this sort of task, runs extremely fast, and is used millions of times every day on *nix systems around the world.