0

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

glenn jackman
  • 238,783
  • 38
  • 220
  • 352
  • Use a loop for this. – Richard Jun 29 '15 at 10:45
  • possible duplicate of [How can I repeat a character in bash?](http://stackoverflow.com/questions/5349718/how-can-i-repeat-a-character-in-bash) – Paul R Jun 29 '15 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 Jun 29 '15 at 10:54

3 Answers3

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 " ")
anubhava
  • 761,203
  • 64
  • 569
  • 643
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.

Mohit Jain
  • 30,259
  • 8
  • 73
  • 100
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"; }
Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
  • Thanks Tom Fenech. I got it now. I used typeset for it. Ex : typeset -L11 x=""; –  Jun 29 '15 at 11:53
  • Also i will definitely try using perl with my shell scripting –  Jun 29 '15 at 11:54
  • 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. – Tom Fenech Jun 29 '15 at 11:55
  • 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. –  Jun 29 '15 at 12:09