Rotate a file to keep it at a certain length.
# the non-portable way to delete a line from the end of a file: # `sed '$d' "#{filename}" > temporary` # `mv -f temporary #{filename}` # FIXME: This is probably a terribe way to do things. Reading the entire file into an array? Bad idea.. def rotate_file(filename, maximum_lines_kept) if File.exists?(filename) == false then raise "ERROR: '#{filename}' does not exist!" end # Read the file in. output = [] File.open(filename, 'r+').each { |line| output << line.chomp } # If we already have a small file, then don't do anything with it. if output.size <= maximum_lines_kept then return nil end File.open(filename, 'w') { |f| # prepare 'filename' for overwriting content # Output the right number of lines, converting the array into strings again. f.print(output[output.size - maximum_lines_kept..-1].join("\n")) f.print("\n") } # @file is automatically closed end
Last updated 2016-12-27 at 21:26:10