Home > OS >  Prevent `cat` from leaving characters after carriage return ("\r")
Prevent `cat` from leaving characters after carriage return ("\r")

Time:08-03

Problem

I'm working on a progress bar that mimics the timer from the {pbapply} package:

| | 10% ~calculating

After the progress bar figures out how much time is remaining, the progress bar turns over:

| | 12% ~22s

So far, I have been able to mimic this latter feature. However, when trying to add the ~calculating text, I achieve this result:

| | 12% ~22sulating

I would like to make calculating disappear and not leave text over so that only ~22s is displayed.

Toy example

A toy example of this behavior is demonstrated here:

# Toy example
for(i in 1:100){
  
  # Sleep for a quarter second
  Sys.sleep(0.25)
  
  # Update progress
  if(i < 10){
    
    cat(
      sprintf(
        paste0("\r |%-49s| %s"), # Timer setup
        paste(rep(" ", i / 2), collapse = ""), # Internal fill
        paste0(i, "% ~calculating") # Percent complete and time remaining
      )
    )
    
  }else{
    
    # Timing
    timing <- round((100 - i) * 0.25)
    
    cat(
      sprintf(
        paste0("\r |%-49s| %s"), # Timer setup
        paste(rep(" ", i / 2), collapse = ""), # Internal fill
        paste0(i, "% ~", timing, "s") # Percent complete and time remaining
      )
    )
  }
  
}

Question

How can I avoid ~22sulating and instead have 22s while keeping the preliminary ~calculating?

Things I've tried:

\f = flushes entire console

flush.console() = does nothing as far as I can tell

CodePudding user response:

Seems like you need enough whitespace characters asfter the "s" to cover up the string "ulating".

paste0(i, "% ~", timing, "s       ")
  •  Tags:  
  • r
  • Related