My current code looks like this: x=${y:0:40}, which limits the length of string to 40 characters. In case of string being shorter than 40 characters, is it possible to fill the trailing places with spaces?

So if my y="very short text"

I would like my y to be:

y="very short text (+25 trailing spaces)"

share|improve this question

If those characters are all single-byte, that is if you're in a locale where the charset is single-byte (like iso8859-1) or if the locale's charset is UTF-8 but the text is ASCII only, you can do:

printf -v y %-40.40s "$y"

That will cover both truncating and padding.

If not, you can always add 40 spaces and use your ${y:0:40} approach.

printf -v pad %40s
y=$y$pad
y=${y:0:40}

zsh has dedicated operators for left and right padding:

y=${(r:40:)y}

(also does truncation). zsh's printf counts in characters instead of bytes, so wouldn't have bash's issue above. However note that you need zsh 5.3 or newer for the -v option.

See also this answer to a related question for more details if you're faced with characters that don't all have the same width.

share|improve this answer

You should try printf:

printf '%-40s' "$y"
share|improve this answer

Pure bash:

ten="          " 
forty="$ten$ten$ten$ten" 
y="very short text"
y="${y:0:40}${forty:0:$((40 - ${#y}))}"
echo "'${y}'"

The method is to add 0-40 spaces to every string after truncating it.

Output, (note the single quote positions):

'very short text                         '
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.