0

I have a variable : str='abc'

I would like to copy it n times, with a space between each string, so the echo gives, for n=3 :

echo $str
abc abc abc

I don't want a space after the last abc

I've already seen the link mentionned but they doesn't help. The last answer from @Amadan is the good one thanks, but I can't accept it :/

Will
  • 1,792
  • 2
  • 23
  • 44
UltimeCactus
  • 73
  • 1
  • 6
  • 2
    Possible duplicate of [How to duplicate string in Bash?](https://stackoverflow.com/q/16484887/608639), [Linux command to repeat a string n times](https://superuser.com/q/86340/173513), [How to duplicate strings in each line using bash?](https://stackoverflow.com/q/32001182/608639), [How can I repeat a character in Bash?](https://stackoverflow.com/q/5349718/608639), etc. – jww Jul 01 '19 at 12:07
  • @jww. I thought I looked through all of those, but the space separator makes this a non-duplicate – Mad Physicist Jul 01 '19 at 12:14
  • Here's something relevant though: https://superuser.com/a/462400/297512 – Mad Physicist Jul 01 '19 at 12:15
  • 4
    `str=$(yes "$str" | head -3 | xargs echo)` – Amadan Jul 01 '19 at 12:15

1 Answers1

0

One more way:

eval echo {1..$n} | sed "s/[[:digit:]]*/${var}/g"

Example:

n=3
var=abc

eval echo {1..$n} | sed "s/[[:digit:]]*/${var}/g"
abc abc abc
sungtm
  • 547
  • 3
  • 12
  • Note: has problems when `$var` has regexp special characters (or slash); fine otherwise. – Amadan Jul 02 '19 at 01:57
  • @Amadan, is it OK by replacing '/' with '|' symbol in sed delimiters like `eval echo {1..$n} | sed "s|[[:digit:]]*|${var}|g"` ? – sungtm Jul 02 '19 at 04:21
  • Of course. But then your variable is restricted from having `|` in it. – Amadan Jul 02 '19 at 04:22