【问题标题】:Is there way to replace lines without clearing the screen?有没有办法在不清除屏幕的情况下更换线条?
【发布时间】:2022-01-25 05:45:55
【问题描述】:
printf "line one\n"
printf "line two\n"

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

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

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

我想做什么:

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

我想要的输出:

line three
line two

【问题讨论】:

    标签: linux bash shell printf echo


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      您可以通过打印特殊的转义序列在 bash 脚本中移动光标,试试这个代码:

      #!/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"
      

      关于 ANSI 转义序列的更多信息:https://tldp.org/HOWTO/Bash-Prompt-HOWTO/c327.html

      【讨论】:

      • tput 可能比这更便携,因为它将处理非 ANSI 终端(如果安装了适当的终端数据)。然而,ANSI 转义被广泛使用,因此可能不值得为此浪费太多时间。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-13
      • 1970-01-01
      • 2015-07-12
      • 2019-04-02
      • 1970-01-01
      相关资源
      最近更新 更多