Search code examples
linuxconsolecharactererase

How do I erase printed characters in a console application(Linux)?


I am creating a small console app that needs a progress bar. Something like...

Conversion: 175/348 Seconds   |==========          |  50%

My question is, how do you erase characters already printed to the console? When I reach the 51st percentage, I have to erase this line from the console and insert a new line. In my current solution, this is what happens...

Conversion: 175/348 Seconds   |==========          |  50%
Conversion: 179/348 Seconds   |==========          |  52%
Conversion: 183/348 Seconds   |==========          |  54%
Conversion: 187/348 Seconds   |===========         |  56%

Code I use is...

print "Conversion: $converted_seconds/$total_time Seconds   $progress_bar  $converted_percentage%\n";

I am doing this in Linux using PHP(only I will use the app - so please excuse the language choice). So, the solution should work on the Linux platform - but if you have a solution that's cross platform, that would be preferable.


Solution

  • I don't think you need to apologize for the language choice. PHP is a great language for console applications.

    Try this out:

    <?php
    for( $i=0;$i<10;$i++){
      print "$i \r";
      sleep(1);
    }
    ?>
    

    The "\r" will overwrite the line with the new text. To make a new line you can just use "\n", but I'm guessing you already knew that.

    Hope this helps! I know this works in Linux, but I don't know if it works in Windows or other operating systems.