简体   繁体   English

bash printf-如何在同一行中将文本右对齐而不删除先前的输出

[英]bash printf - how to align text to right in the same line without deleting previous output

I'm trying to have in script Done or Fail statuses aligned to the right of previous text. 我正在尝试使脚本的Done或“ Fail状态与上一文本的右侧对齐。 But not eg 50 chars from last character, but 50 chars from left side of terminal. 但是不是最后一个字符起的50个字符,而是从终端左侧起的50个字符。 I'm not printing it using single, but multiple printf 's. 我不是使用单个printf来打印它。 In code I have eg 在代码中我有例如

    printf "Creating folder..."
    sleep 2
    mkdir foo
    printf "\r%50.10s\n" "Done"

Unfortunately it keeps me outputting 不幸的是它让我输出

                                                  Done

instead of 代替

    Creating folder...                            Done

Is there a possibility to align text to right in the same line without deleting previous output? 是否有可能在不删除先前输出的情况下在同一行中将文本右对齐?

Debian 8, bash 4.3.30 Debian 8,bash 4.3.30

There are a couple of options, at least. 至少有两个选择。

  1. Simply extend what's already output: 只需扩展已经输出的内容:

     printf "Creating folder..." mkdir foo sleep 2 printf "%32s\\n" "Done" 
  2. Rewrite what was already output: 重写已经输出的内容:

     printf "Creating folder..." mkdir foo sleep 2 printf "\\r%-50s %s\\n" "Creating folder..." "Done" 

I moved the sleep after the mkdir to give you some chance to read error messages from mkdir before the printf kicks in again. 我在mkdir之后移动了sleep ,以便在再次打开printf之前有机会读取mkdir错误消息。

You might want to think about showing the folder name in the messages too. 您可能还想考虑在消息中显示文件夹名称。

You can use an ANSI escape code to explicitly position the cursor in column 50: 您可以使用ANSI转义代码将光标明确定位在第50列中:

printf "Creating folder..."
sleep 2
mkdir foo
printf "\033[50G%s\n" "Done"
        ^^^^^^^^

This does not require calculating a width based on how much was already printed or reprinting the first part of the line. 这不需要根据已经打印的多少或重新打印该行的第一部分来计算宽度。 It does assume a terminal that processes ANSI escape codes, though. 但是,它确实假定终端处理ANSI转义码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM