Is there way to replace lines without clearing the screen?

Viewed 139
printf "line one\n"
printf "line two\n"

After these printouts I want to replace line one and print something else (without using clear). I've tried commands like:

printf "line one\n"
printf "line two\r"

It's not what I want because it replaces the last line line two, not line one.

What I want to do:

printf "line one\n"
printf "line two\n"
sleep 0.5
somecode "line three"

Output I want:

line three
line two
2 Answers

This can be done with tput, eg:

EraseToEOL=$(tput el)                 # save control code for 'erase to end of line'
tput sc                               # save pointer to current terminal line

printf "line one - a long line\n"
printf "line two\n"
sleep 0.5

tput rc                               # return cursor to last cursor savepoint (`tput sc`)
printf "line three${EraseToEOL}\n"    # print over `line one - a long line`; print `$EraseToEOL` to clear rest of line (in case previous line was longer than `line three`)
printf "\n"                           # skip over 'line two'

This will initially print:

line one - a long line                # `tput sc` will point to this line
line two
<cursor>                              # cursor is left sitting on this line

Then after sleeping 0.5 seconds tput rc will cause the cursor to move 'up' 2 lines before executing the last 2x printf commands:

line three                            # old 'line one - a long line` is overwritten
line two                              # `printf "\n"` won't print anything new on this line so the old contents won't be overwritten, while the cursor will be moved to the next line
<cursor>                              # cursor is left sitting on this line

Another example: here

Some documentation: here and here

you can move the cursor in bash scripts via printing special escape sequences, try this code:

#!/bin/bash

# print first line
printf "first line is long\n"
# print second line
printf "line 2\n"
sleep 1
# move cursor two steps UP
printf "\033[2A"
# print line 3 (without \n)
printf "line #3"
# clear rest of first line
# and move cursor two steps down
printf "\033[K\r\033[2B"

more about ANSI Escape Sequences: https://tldp.org/HOWTO/Bash-Prompt-HOWTO/c327.html

Related