Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting contents of file after a specific line in ruby

Tags:

file

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.

like image 256
user Avatar asked Nov 17 '25 18:11

user


1 Answers

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.

like image 56
steenslag Avatar answered Nov 20 '25 17:11

steenslag



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!