0

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!

joshlf
  • 21,822
  • 11
  • 69
  • 96

2 Answers2

1

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

Justinas
  • 41,402
  • 5
  • 66
  • 96
  • I'm not too up on the details of terminal compatibility. Would a terminal's support for moving a cursor with `\r` and `\b` and the like imply that it would also support the more complex multi-character escape sequences? – joshlf Aug 21 '14 at 10:39
  • @synful I think it will support complex sequences – Justinas Aug 21 '14 at 10:58
  • OK sounds good. I should read up more on terminal features; it's really cool stuff. Are there basically just VT100-compatible terminals and then all the really old and/or weird crap (essentially, DOS, Windows cmd.exe, and truly legacy stuff), or are there other terminals in use today that are non-VT100-compatible? If you don't know the answer, I can always go not be lazy and Google it :) – joshlf Aug 21 '14 at 11:03
0

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.

Chuck Pergiel
  • 151
  • 2
  • 14