33

I have printed some text using println! and now I need to clear the terminal and write the new text instead of the old. How can I clear all the current text from terminal?

I have tried this code, but it only clears the current line and 1 is still in the output.

fn main() {
    println!("1");
    print!("2");
    print!("\r");
}
Shepmaster
  • 326,504
  • 69
  • 892
  • 1,159
Haru Atari
  • 1,375
  • 2
  • 15
  • 29
  • 10
    This is no duplicate! This is asking for a way to clear the terminal. The linked "duplicate" is about clearing the current line. The question also states that clearing the current line is not helpful. – itmuckel Oct 13 '17 at 22:41

4 Answers4

48

You can send a control character to clear the terminal screen.

fn main() {
    print!("{}[2J", 27 as char);
}

Or to also position the cursor at row 1, column 1:

print!("{esc}[2J{esc}[1;1H", esc = 27 as char);
Shepmaster
  • 326,504
  • 69
  • 892
  • 1,159
minghan
  • 903
  • 6
  • 12
20
print!("\x1B[2J\x1B[1;1H");

This will clear the screen and put the cursor at first row & first col of the screen.

Markus
  • 1,875
  • 5
  • 23
  • 40
3

Solutions provided by the upvoted answers did not work the way I wanted to. The \x1B[2J\x1B[1;1H sequency only scrolls down the terminal so it actually hides the content and does not clear it. As I wanted to run and infinite loop that re-renders the content shown to the user, this was problem since the scrollbar of my terminal window was shrinking with every "tick".

Inspired from Clear a terminal screen for real I am using

print!("{esc}c", esc = 27 as char);

which works great for me. There might be some drawback on other systems than I use (Ubuntu), I do not know that.

Dan Charousek
  • 82
  • 1
  • 5
0

Try this in the Linux or macOS terminal:

std::process::Command::new("clear").status().unwrap();

In Windows one:

std::process::Command::new("cls").status().unwrap();

This basically sends the "clear" command to terminal.

Shepmaster
  • 326,504
  • 69
  • 892
  • 1,159
moloko824
  • 31
  • 1