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

标签 linux bash shell printf echo

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/

相关文章:

bash - 如何在bash中计算日期范围内的文件行数?

bash - 如何检查后台作业是否存在? ( bash )

linux - 从已编译库的反汇编中仅获取十六进制字节值

linux - phpinfo() 在浏览器中未显示正确的版本

linux - 期望程序从文件发送命令

c - 如何在支持gnu99的gcc中处理 "warning: inline function ` *stat6 4` declared but never defined"

linux - Linux 脚本中 if 表达式中的 -z 值是什么意思?

bash - 如何在 shell 脚本中提取字符串的前两个字符?

linux - 将全文文件路径分配给变量并使用变量作为 sh 文件中的文件路径

c# - Linux 生物信息学工具