Skip to content

Instantly share code, notes, and snippets.

@zerowidth
Created May 23, 2011 23:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zerowidth/987844 to your computer and use it in GitHub Desktop.
Save zerowidth/987844 to your computer and use it in GitHub Desktop.
test out truncating a file in place
#!/usr/bin/env ruby
log = "big.log"
words = %w(foo bar baz blech mumble what no ack aiee)
File.open(log, 'w') do |file|
1000.times do |n|
content = (0..(rand(100) + 10)).map { words[rand(words.size)] }
file.puts "#{n} #{content.join ' '}"
end
end
reader = File.open(log, 'r')
writer = File.open(log, 'r+')
writer.rewind
# assume no overlap between reading and writing!
reader.each_line.with_index do |line, n|
next if n < 10
writer.puts line
end
writer.truncate(writer.pos)
reader.close
writer.close
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment