Multiplying strings in bash script

三世轮回 提交于 2020-01-01 10:13:21

问题


I know that if I do print ("f" + 2 * "o") in python the output will be foo.

But how do I do the same thing in a bash script?


回答1:


You can use bash command substitution to be more portable across systems than to use a variant specific command.

$ myString=$(printf "%10s");echo ${myString// /m}           # echoes 'm' 10 times
mmmmmmmmmm

$ myString=$(printf "%10s");echo ${myString// /rep}         # echoes 'rep' 10 times
reprepreprepreprepreprepreprep

Wrapping it up in a more usable shell-function

repeatChar() {
    local input="$1"
    local count="$2"
    printf -v myString "%s" "%${count}s"
    printf '%s\n' "${myString// /$input}"
}

$ repeatChar str 10
strstrstrstrstrstrstrstrstrstr



回答2:


In bash you can use simple string indexing in a similar manner

#!/bin/bash
oos="oooooooooooooo"
n=2
printf "%c%s\n" 'f' ${oos:0:n}

output

foo

Another approach simply concatenates characters into a string

#!/bin/bash
n=2
chr=o
str=
for ((i = 0; i < n; i++)); do 
    str="$str$chr"
done
printf "f%s\n" "$str"

Output

foo

There are several more that can be used as well.




回答3:


You could simply use loop

$ for i in {1..4}; do echo -n 'm'; done
mmmm



回答4:


That will do:

printf 'f'; printf 'o%.0s' {1..2}; echo

Look here for explanations on the "multiplying" part.




回答5:


You can create a function to loop a string for a specific count and use it in the loop you are executing with dynamic length. FYI a different version of oter answers.

  line_break()
    {
        for i in `seq 0 ${count}`
        do
          echo -n "########################"
        done
    }

    line_break 10

prints: ################



来源:https://stackoverflow.com/questions/38868665/multiplying-strings-in-bash-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!