0

I want a variable having 'n' spaces in it. How can i do it ?

3
  • Use a loop for this. Commented Jun 29, 2015 at 10:45
  • possible duplicate of How can I repeat a character in bash? Commented 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. Commented Jun 29, 2015 at 10:54

3 Answers 3

1

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 " ")
Sign up to request clarification or add additional context in comments.

6 Comments

Looks good - is that a bash-only thing or will it work on other POSIX shells?
On my OSX it worked using /bin/sh as well as bash
thanks anubhava. I got it now. I used typeset for it. Ex : typeset -L11 x="";
Using typeset I am getting sh: typeset: -L: invalid option
Anubhava- i am using ksh. can you try by adding this to the script #!/usr/bin/ksh
|
1

I 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

0

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"; }

4 Comments

Thanks Tom Fenech. I got it now. I used typeset for it. Ex : typeset -L11 x="";
Also i will definitely try using perl with my shell scripting
You're welcome. If you have found your own solution to the problem, you should post it as an answer so that other people can use it in the future.
Hey Tom , can you answer this as well ------Example : Say i have 3 variables x=1,y=2,z=3. I am adding to abc.dat file like below : echo "${x}${y}${z}" >> abc.dat; But file has content as : 1 2 3 meaning new lines are coming. I want like this : 123 without new lines.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.