A clock utility, via console hackery

[This article was first published on 4D Pie Charts » R, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

A discussion on StackOverflow today shows an interesting use of special characters inside the cat function.

The most common special characters that you may have come across are the tab and newline characters, represented by \t and \n respectively. Try them for yourself.

cat("Red\tlorry\nYellow\tlorry\n")

cat also respects the backspace character, \b, and the carriage return character, \r, which means that you can delete things. Usually, this isn’t very useful, but it allows us to overwrite text in the console.

cat("ab\bc")      #\b removes the previous character
cat("abc\rde")    #\r removes everything to the start of the line

Here’s a simple clock utility, adapted from Mark, Zach and DWin’s code in the linked question, that uses this technique.

clock <- function()
{
  repeat
  {
    cat("\r", format(Sys.time(), "%H:%M:%S"))
    flush.console()
    Sys.sleep(1)
  }
}
clock()

Press escape to exit the clock utility. You can see a complete list of special characters over at asciitable.com.


Tagged: ascii, clock, r

To leave a comment for the author, please follow the link and comment on their blog: 4D Pie Charts » R.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)