Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear the terminal screen in Rust after a new line is printed?

Tags:

terminal

rust

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"); } 
like image 915
Haru Atari Avatar asked Jan 17 '16 09:01

Haru Atari


People also ask

How do you clean terminal output?

A common way to do that is to use the `clear` command, or its keyboard shortcut CTRL+L.

How do I clear the screen in a bash script?

When using the bash shell, you can also clear the screen by pressing Ctrl + L .


2 Answers

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); 
like image 68
minghan Avatar answered Oct 26 '22 17:10

minghan


print!("\x1B[2J\x1B[1;1H"); 

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

like image 21
Muhammad Tariq Baig Avatar answered Oct 26 '22 17:10

Muhammad Tariq Baig