如何将字符串扩展到一定长度 [英] How to extend string to certain length
问题描述
基本上现在我的程序给了我这个输出:
Hey basically right now my program gives me this output:
BLABLABLA
TEXTEXOUAIGJIOAJGOAJFKJAFKLAJKLFJKL
TEXT
随机字符超出限制的更多文本
BLABLABLA
TEXTEXOUAIGJIOAJGOAJFKJAFKLAJKLFJKL
TEXT
MORE TEXT OF RANDOM CHARACTER OVER LIMIT
是for循环的结果.现在,这就是我想要的:
which is a result of for loop. Now here's what i want:
- 如果字符串超过10个字符,则剪掉其余部分并添加两个点& ;;以冒号结尾"..:"
- 否则(如果字符串少于10个字符)用空格填充空格,以便使用
所以在我提供的示例中,我想要这样的东西作为输出:
so on the example i provided i'd want something like this as output:
BLABLABLA :
TEXTEXOUA..:
TEXT :
MORE TEXT..:
我也解决了问题的第一部分(当字符超过10个字符时),只有第二部分给我带来了麻烦.
I also solved the first part of the problem (when its over 10 characters), only the second one gives me trouble.
AMOUNT=definition here, just simplyfying so not including it
for (( i=1; i<="$AMOUNT"; i++ )); do
STRING=definition here, just simplyfying so not including it
DOTS="..:"
STRING_LENGTH=`echo -n "$STRING" | wc -c`
if [ "$STRING_LENGTH" -gt 10 ]
then
#Takes
STRING=`echo -n "${STRING:0:10}"$DOTS`
else
#now i dont know what to do here, how can i take my current $STRING
#and add spaces " " until we reach 10 characters. Any ideas?
fi
推荐答案
Bash提供了一种简单的方法来获取存储在变量中的字符串的长度: $ {#STRING}
Bash provides a simple way to get the length of a string stored in a variable: ${#STRING}
STRING="definition here, just simplyfying so not including it"
if [ ${#STRING} -gt 10 ]; then
STR12="${STRING:0:10}.."
else
STR12="$STRING " # 12 spaces here
STR12="${STR12:0:12}"
fi
echo "$STR12:"
您发布的预期输出与问题中的要求不符.我试图遵循这些要求,而忽略了示例预期输出和您发布的代码.
The expected output you posted doesn't match the requirements in the question. I tried to follow the requirements and ignored the sample expected output and the code you posted.
这篇关于如何将字符串扩展到一定长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!