3

Probably a simple question, but I need to delete the contents of a file after a specific line number? So I wan't to keep the first e.g 5 lines and delete the rest of the contents of a file. I have been searching for a while and can't find a way to do this, I am an iOS developer so Ruby is not a language I am very familiar with.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user
  • 115
  • 8

2 Answers2

5

That is called truncate. The truncate method needs the byte position after which everything gets cut off - and the File.pos method delivers just that:

File.open("test.csv", "r+") do |f|
  f.each_line.take(5)
  f.truncate( f.pos )
end

The "r+" mode from File.open is read and write, without truncating existing files to zero size, like "w+" would.

The block form of File.open ensures that the file is closed when the block ends.

steenslag
  • 79,051
  • 16
  • 138
  • 171
2

I'm not aware of any methods to delete from a file so my first thought was to read the file and then write back to it. Something like this:

path = '/path/to/thefile'
start_line = 0
end_line = 4
File.write(path, File.readlines(path)[start_line..end_line].join)

File#readlines reads the file and returns an array of strings, where each element is one line of the file. You can then use the subscript operator with a range for the lines you want

This isn't going to be very memory efficient for large files, so you may want to optimise if that's something you'll be doing.

Community
  • 1
  • 1
james246
  • 1,884
  • 1
  • 15
  • 28