How to extend string to certain length

2019-03-04 05:34发布

Hey basically right now my program gives me this output:

BLABLABLA
TEXTEXOUAIGJIOAJGOAJFKJAFKLAJKLFJKL
TEXT
MORE TEXT OF RANDOM CHARACTER OVER LIMIT

which is a result of for loop. Now here's what i want:

  • if the string raches over 10 characters, cut the rest and add two dots & colon to the end "..:"
  • otherwise (if the string has less than 10 characters) fill the gap with spaces so they're alligned

so on the example i provided i'd want something like this as output:

BLABLABLA  :  
TEXTEXOUA..:  
TEXT       :
MORE TEXT..:

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 shell
2条回答
我欲成王,谁敢阻挡
2楼-- · 2019-03-04 06:20

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.

查看更多
smile是对你的礼貌
3楼-- · 2019-03-04 06:21

Use printf:

PADDED_STRING=$(printf %-10s $STRING)
查看更多
登录 后发表回答