Like this picture of apt-get, how can I print something at the end of the line, just like the speed on the screen. Although I can use escape like \e[C
to make it move several columns to the right and print, but the speed varies and the string length varies. Can anyone tell me how to do this? I am currently programming using bash. Thanks.![apt-get](https://i.stack.imgur.com/yaP7G.png)
通常您会在环境变量中找到控制台窗口的宽度COLUMNS https://www.gnu.org/software/bash/manual/bashref.html#index-COLUMNS,但这并不完全可靠。更可靠的解决方案是使用tput
带有参数的实用程序(ncurses 的一部分,但可以独立使用)cols
:
$ echo $COLUMNS
148
$ tput cols
148
分割文本的一个简单方法是使用 Posix 标准printf
实用程序首先打印要在右边距上对齐的文本并填充到列宽,然后输出回车符(\r
) 将光标返回到行首,然后打印要在左边距对齐的文本。最后换行符将移动到下一行。或者,在代码中:
# Call it like this:
# print_both_sides "This goes on the left" "and this goes on the right."
print_both_sides() {
printf "\r%*s\r%s\n" $(tput cols) "$2" "$1";
}
The printf
格式使用的标准功能*
替换字段宽度和精度格式修饰符;这*
意味着相应的数字应该从参数中获取。在这种情况下,我使用$(tput cols)
-- 即控制台窗口的宽度 -- 作为格式代码的第一个参数%*s
,它具有右填充下一个字符串参数的效果("$2"
)在其宽度恰好是控制台宽度的字段中。
我在输出的开头添加了一个额外的回车符,以防光标当前不在左边距。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)