右文本对齐 - bash
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4239010/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
right text align - bash
提问by cubrilo
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=
file=
echo
echo -e "length = $length \t file = $file "
f=`fold -w$length $file > output`
while read line
do
echo "line is $line"
done < "output"
thanks
谢谢
回答by icyrock.com
Try:
尝试:
printf "%40.40s\n" "$line"
This will make it right-aligned with width 40. If you want no truncation, drop .40(thanks Dennis!):
这将使其与宽度 40 右对齐。如果您不想截断,请删除.40(感谢丹尼斯!):
printf "%40s\n" "$line"
For example:
例如:
printf "%5.5s\n" abc
printf "%5.5s\n" abcdefghij
printf "%5s\n" abc
printf "%5s\n" abcdefghij
will print:
将打印:
abc
abcde
abc
abcdefghij
回答by Wesley Rice
Your final step could be
你的最后一步可能是
sed -e :a -e 's/^.\{1,$length\}$/ &/;ta'

