user
user

Reputation: 115

Deleting contents of file after a specific line in ruby

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.

Upvotes: 3

Views: 940

Answers (2)

steenslag
steenslag

Reputation: 80065

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.

Upvotes: 5

james246
james246

Reputation: 1904

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.

Upvotes: 2

Related Questions