4

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?

2
  • 2
    Why don't you print "Done" with a lot of spaces after? Commented Dec 2, 2012 at 19:32
  • @SergioTulentsev because some terminals actually do line-wrapping. Commented Dec 2, 2012 at 20:11

1 Answer 1

7

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'
Sign up to request clarification or add additional context in comments.

2 Comments

clear = `tput el` doesn't work where the tput command is not available (e.g. Windows).
Obviously it wouldn't. Not being able to completely rely on that being available is part of the reason I gave other alternatives.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.