Task

Remove a specific line or a number of lines from a file.

This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed).

For the purpose of this task, line numbers and the number of lines start at one, so to remove the first two lines from the file foobar.txt, the parameters should be: foobar.txt, 1, 2

Empty lines are considered and should still be counted, and if the specified line is empty, it should still be removed.

An appropriate message should appear if an attempt is made to remove lines beyond the end of the file.




require 'tempfile'
 
def remove_lines(filename, start, num)
  tmp = Tempfile.open(filename) do |fp|
    File.foreach(filename) do |line|
      if $. >= start and num > 0
        num -= 1
      else
        fp.puts line
      end
    end
    fp
  end
  puts "Warning: End of file encountered before all lines removed" if num > 0
  FileUtils.copy(tmp.path, filename)
  tmp.unlink
end
 
# Test code
def setup(filename, start, remove)
  puts "remove #{remove} lines starting at line #{start}"
  File.open(filename, "w") {|fh| (1..5).each {|i| fh.puts " "*i + i.to_s}}
  puts "before:", File.read(filename)
end
 
def teardown(filename)
  puts "after:", File.read(filename)
  puts
  File.unlink(filename)
end
 
filename = "foobar.txt"
start = 2
[2, 6].each do |remove|
  setup(filename, start, remove)
  remove_lines(filename, start, remove)
  teardown(filename)
end