Mark Heckmann
Mark Heckmann

Reputation: 11431

console output in loops: how to completely clean last cat ouput without adding a line break?

I often add the following to loops to print out some message for each iteration.

for (word in c("a", "long message", "c")) {
  cat("\r", word)
  flush.console()
  Sys.sleep(1)
}

enter image description here

As we see, the message "c" only overwrites part of the previous "long message". I would like to avoid that. The only thing I can come up with is to add extra blanks, e.g.

for (word in c("a", "long message", "c")) {
  cat("\r", word, "                ")
  flush.console()
  Sys.sleep(1)
}

Is there a better approach to get a clean message after a carriage return? Note, that I do not want linebreaks.

UPDATE: @user1981275 posted a solution which is confirmed to work on Linux. Platform independent solutions are still wanted.

Upvotes: 4

Views: 462

Answers (1)

user1981275
user1981275

Reputation: 13370

The ANSI Erase to end of line escape sequence \033[K can be used with cat (see for example here):

for (word in c("a", "long message", "c")) {
  cat("\r", "\033[K", word)
  flush.console()
  Sys.sleep(1)
}

Upvotes: 3

Related Questions