In-place progress output to the console: How to empty the current line

ruby, terminal

Solution

You need to send the sequence of bytes that corresponds to the terminfo variable `clr_eol` (capability name `el`) after using `\r`. There are several ways that you could get that.

Simplest, assume that there's a constant value. On the terminals I've checked it is `\e[K`, but I've only checked a couple. On both of those the following works:

clear = "\e[K"
print "foo 123"
print "\r#{clear}bar\n"

You could also get the value using:

clear = `tput el` 

Or you could use the terminfo gem:

require 'terminfo'
clear = TermInfo.control_string 'el'

Problem

I have a Ruby script that outputs progress messages on the same line, using the carriage return character, like this: ``` print "\r#{file_name} processed." ``` As an example, the output changes from `'file001.html' processed.` to `'file002.html.' processed` and so on until the script completes. I'd like to replace the last progress message with `Done.`, but I can't just write `print "\rDone."` because that piece of code outputs something like this: ``` Done.99.html processed. ``` I guess I have to empty the line after the last progress message and then print `Done.`. How do I do that?

Original source