gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 09:53:33 25 4
gpt4 key购买 nike

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

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

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

这不是我想要的,因为它替换了最后一行第二行,而不是第一行

我想做的事情:

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

我想要的输出:

line three
line two

最佳答案

这可以通过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'

最初会打印:

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

然后在休眠 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

另一个例子:here

一些文档:herehere

关于linux - 有没有办法在不清除屏幕的情况下替换行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64270425/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com