right text align - bash

问题描述:

我有一个问题。 我的文本应该按照指定的宽度右对齐。我已成功地削减产量所需的大小,但我有问题,把一切在右侧right text align - 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" 

感谢

尝试:

printf "%40.40s\n" "$line" 

这将使其与宽度40右对齐。如果您不想截断,请删除.40(谢谢Dennis!):

printf "%40s\n" "$line" 

例如:

printf "%5.5s\n" abc 
printf "%5.5s\n" abcdefghij 
printf "%5s\n" abc 
printf "%5s\n" abcdefghij 

会打印:

abc 
abcde 
    abc 
abcdefghij 
+0

这给我一些奇怪的输出,不知道为什么 – cubrilo 2010-11-21 17:22:08

+0

:)你认为我能猜到输出是什么吗?请在其他评论中发布该问题。如果时间太长,请编辑您的问题并将其发布到那里。 – 2010-11-21 17:25:43

+0

@cubrilo:您可能需要一个'\ n'换行符,以便输出与原始文件中隐含的意图相匹配:'printf'%40.40s \ n“”$ line“'。注意'.40'会导致输出被截断,如果它更长,这可能是你想要的,但是如果不是,你可以省略那部分。 – 2010-11-21 21:53:40

你的最后一步可能是

sed -e :a -e 's/^.\{1,$length\}$/ &/;ta' 
+0

当我把它放在while:f ='fold -w $ lenght $ file> output' while read line do sed -e:a -e's/^。\ {1,$ length \} $/&lt; echo“在sed后,行是$ line” done cubrilo 2010-11-21 17:23:18

+0

@cubrilo:将单引号改为双引号:'sed -e:a -e”s/^。\ {1, $ length \} $ /&/; ta“',但这种方式很慢,因为它循环直到字符串足够长。 – 2010-11-21 21:56:13