2 may
2021

Properly overwrite current line in terminal

In most terminals, if you haven't printed a newline character (or line feed; \n), printing a carriage return (\r) will reset your cursor to the beginning of the line so that subsequent characters overwrite what you've already output on the current line.

However, if you don't output enough characters to fully overwrite the previous contents of the line, the remaining characters will stay there. So, for example, the following pseudocode:

print "goodbye"
print "\rhello"

would result in helloye.

I'm wondering: is there any way to actually clear these remaining characters? I could simply keep track of them and then overwrite them with spaces, but that would, a) require me to keep track of them, and, b) still have trailing space characters, which isn't ideal, and I'd prefer not to do (I'm looking for a general solution that I can use whenever I come across this problem in the future). Any advice would be great; thanks!

COMENTARIOS

Chuck Pergiel

I used a leading carriage return a long time ago and it worked pretty well. I just tried it again on Linux Gnome Terminal program and it doesn't seem to work: nothing shows up on the screen. Changed it back to using a trailing line feed and every line I print gets displayed, but not overwritten. I suspect the lack of a line feed is what is keeping it from getting actually sent to the display.

See this about flushing.

justinas

Try using terminal escape

To clear from beginning of line to cursor: echo -e "\033[1K"
To clear line: echo -e "\033[2K"

Assuming you have VT100-compatible terminal or emulator

DEJA TU COMENTARIO

© 2017 website by Rubit Corporation