Removing the first line in a text file

Even simpler:

open("file_to_read") do input
    open("test.txt", "w") do output
        for line in Iterators.drop(eachline(input), 1)
            println(output, line)
        end
    end
end

If you want to maximize speed, and avoid the extraneous newline pointed out by @yuyichao, it would be faster to read everything after the newline in a block:

open("file_to_read") do input
    readuntil(input, '\n')
    write("file_to_write", read(input))
end

This implementation is even shorter than the code based on eachline. (And it will be vastly faster than spawning a Unix program like tail, not to mention being more portable.)

The only downside of this approach is that it might take a lot of memory if you have an enormous file. A more general implementation would probably read the data in large blocks, similar to this code.

8 Likes