How to duplicate string in bash?

2020-02-16 02:58发布

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?

4条回答
我想做一个坏孩纸
2楼-- · 2020-02-16 03:21
$ 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
查看更多
Animai°情兽
3楼-- · 2020-02-16 03:22

This should work:

str="kallel"
str2="${str}"
while (( ${#str2} < 20 ))
do
  str2="${str2}${str}"
done
str2="${str2:0:20}"
查看更多
beautiful°
4楼-- · 2020-02-16 03:22

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
查看更多
The star\"
5楼-- · 2020-02-16 03:29

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`
查看更多
登录 后发表回答