有没有办法在不清除屏幕的情况下替换行?

مري*_*ربي 2 linux bash shell printf echo

printf "line one\n"
printf "line two\n"
Run Code Online (Sandbox Code Playgroud)

在这些打印输出之后,我想替换第一并打印其他内容(不使用clear)。我试过这样的命令:

printf "line one\n"
printf "line two\r"
Run Code Online (Sandbox Code Playgroud)

这不是我想要的,因为它替换了最后一行line two,而不是line one.

我想做的事:

printf "line one\n"
printf "line two\n"
sleep 0.5
somecode "line three"
Run Code Online (Sandbox Code Playgroud)

我想要的输出:

line three
line two
Run Code Online (Sandbox Code Playgroud)

mar*_*rkp 6

这可以通过tput,例如:

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'
Run Code Online (Sandbox Code Playgroud)

这将最初打印:

line one - a long line                # `tput sc` will point to this line
line two
<cursor>                              # cursor is left sitting on this line
Run Code Online (Sandbox Code Playgroud)

然后在休眠 0.5 秒tput rc后将导致光标在执行最后 2x 个printf命令之前“向上”移动 2 行:

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
Run Code Online (Sandbox Code Playgroud)

其他一些例子:这里这里

一些文档:这里这里