文本右对齐 - bash
我有一个问题。 我的文本应按指定宽度右对齐。我已经设法将输出剪切到所需的大小,但我无法将所有内容放在右侧,
这就是我得到的:
#!/usr/local/bin/bash
length=$1
file=$2
echo $1
echo -e "length = $length \t file = $file "
f=`fold -w$length $file > output`
while read line
do
echo "line is $line"
done < "output"
谢谢
I have one problem.
My text should be aligned by right in specified width. I have managed to cut output to the desired size, but i have problem with putting everything on right side
Here is what i got:
#!/usr/local/bin/bash
length=$1
file=$2
echo $1
echo -e "length = $length \t file = $file "
f=`fold -w$length $file > output`
while read line
do
echo "line is $line"
done < "output"
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试:
这将使其与宽度 40 右对齐。如果您不想截断,请删除
.40
(感谢丹尼斯!):例如:
将打印:
Try:
This will make it right-aligned with width 40. If you want no truncation, drop
.40
(thanks Dennis!):For example:
will print:
这是一个非常古老的问题(2010),但它是谷歌的最高结果,所以也可以。在此处现有的答案中,一个是不根据终端宽度进行调整的猜测,另一个是调用 sed ,这不必要地昂贵。
printf 解决方案更好,因为它是 bash 内置函数,因此它不会减慢速度,但不是猜测 - bash 为您提供 $COLUMNS 来告诉您正在处理的终端窗口有多宽。
因此,虽然您可以显式对齐,例如第 40 列:
您可以根据终端宽度调整它的大小:(
因为我们在这里混合了语法,所以我们使用了 bash 变量的完整形式语法,即 ${COLUMNS :
现在我们已经释放了所有 sed 处理时间,我们可以将它用于其他用途
This is a very old question (2010) but it's the top google result, so might as well. Of the existing answers here, one is a guess that doesn't adjust for terminal width, and the other one invokes sed which is unnecessarily costly.
The printf solution is better as it's a bash builtin, so it vwon't slow things down, but instead of guessing - bash gives you $COLUMNS to tell you how wide the terminal window you're dealing with is.
so while you can explicitly align to, say the 40th column:
You can size it for whatever your terminal width is with:
(since we're mixing up syntax here, we have used the full form syntax for a bash variable i.e. ${COLUMNS} instead of $COLUMNS, so that bash can identify the variable from the other syntax
In action .. now that we've freed up all that sed processing time, we can use it for something else maybe:
你的最后一步可能是
Your final step could be