1

I have the following string in bash

str="kallel"

I want to create from str an str2. The str2 contains str duplicated till the length = 20. So the result should be like this:

str2="kallelkallelkallelka"

How to do in in bash?

ulidtko
  • 14,740
  • 10
  • 56
  • 88
MOHAMED
  • 41,599
  • 58
  • 163
  • 268

4 Answers4

7
$ str="kallel"

$ str2=$(printf "$str%.0s" {1..20})
$ echo "$str2"
kallelkallelkallelkallelkallelkallelkallelkallelkallelkallelkallelkallelkallelkallelkallelkallelkallelkallelkallelkallel

$ str2=$(printf "$str%.0s" {1..3})
$ echo "$str2"
kallelkallelkallel

$ n=5
$ str2=$(printf "$str%.0s" $(seq "$n"))
$ echo "$str2"
kallelkallelkallelkallelkallel
Ed Morton
  • 188,023
  • 17
  • 78
  • 185
  • 1
    Gotta say I love this use of printf. It took some noodling, but now I see that printf will repeat it's format string for every argument passed to it (if there are more arguments than replaceable % parameters). The %.0s eats up an argument but adds it to the output as 0 length. Even though it's a little obscure, I think it's a better solution than yes | head | xargs | sed | cut that I presented. – Mark Apr 16 '21 at 13:40
4

This should work:

str="kallel"
str2="${str}"
while (( ${#str2} < 20 ))
do
  str2="${str2}${str}"
done
str2="${str2:0:20}"
twalberg
  • 59,951
  • 11
  • 89
  • 84
  • Line #2 (`str2="${str}"`) is redundant. – devnull May 10 '13 at 15:08
  • @devnull How so? It's assigning the value of one variable (`${str}`) as the initial value of a second variable (`str2`) before the loop... It reduces the loop count by one as well as overwriting any previous value `str2` might have had, avoiding an explicit `str2=""`... – twalberg May 10 '13 at 15:10
  • `str2` is unassigned, so length is zero. Try `echo ${#foo}`. – devnull May 10 '13 at 15:21
  • @devnull It's *probably* unassigned, but I don't know that for sure if this is part of a bigger script. Better to be safe. – twalberg May 10 '13 at 15:23
2

I'd go for a while loop personally then cut it at the end.

While the length of str2 is less than 20, add str to str2. Then, for good measure, we cut at the end to max 20 characters.

#!/bin/bash
str="kallel"
str2=""
while [ ${#str2} -le 20 ]
do
    str2=$str2$str
done
str2=`echo $str2 | cut -c1-20`
Ewan
  • 14,592
  • 6
  • 48
  • 62
2

I am 100% stealing this answer from Bash : Duplicate a string variable n times but I thought it bore repeating (despite being on a 6 year old question):

$ yes "kallel" | head -20  | xargs | sed 's/ //g' | cut -c1-20
kallelkallelkallelka
Mark
  • 4,249
  • 1
  • 18
  • 27