I want a variable having 'n' spaces in it. How can i do it ?
-
Use a loop for this.Richard– Richard2015-06-29 10:45:58 +00:00Commented Jun 29, 2015 at 10:45
-
possible duplicate of How can I repeat a character in bash?Paul R– Paul R2015-06-29 10:48:35 +00:00Commented Jun 29, 2015 at 10:48
-
1@Paul, assuming that the OP is using bash, then there's some good suggestions there, although most of the answers to that question aren't going to work in other shells.Tom Fenech– Tom Fenech2015-06-29 10:54:36 +00:00Commented Jun 29, 2015 at 10:54
3 Answers
Simplest is to use this special printf format:
n=10
# assign n char length space to var
printf -v var "%*s" $n " "
# check length
echo "${#var}"
10
PS: If printf -v isn't available then use:
var=$(printf "%*s" $n " ")
6 Comments
/bin/sh as well as bashtypeset I am getting sh: typeset: -L: invalid optionI have able to do it by using typeset.
For ex :
typeset -L11 x="";
this will assign 11 spaces to the variable.
Option Operation
-Ln
Left-justify. Remove leading spaces; if n is given, fill with spaces or truncate on right to length n.
-Rn
Right-justify. Remove trailing spaces; if n is given, fill with spaces or truncate on left to length n.
-Zn
If used with -R, add leading 0's instead of spaces if needed. If used with -L, strips leading 0's. By itself, acts the same as -RZ.
-l
Convert letters to lowercase.
-u
Convert letters to uppercase.
Comments
You could use a function to return a given number of spaces:
n_spaces() { n=$1; while [ $((n--)) -gt 0 ]; do printf ' '; done; }
Then to assign to a variable, use var=$(n_spaces 5).
Obviously there's a lot of ways you could do this using other tools/languages such as Perl:
n_spaces() { perl -se 'print " " x $x' -- -x="$1"; }