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.