在bash脚本中乘以字符串

Jak*_*nda 5 string bash concatenation

我知道如果我print ("f" + 2 * "o")在python中输出将是foo.

但是如何在bash脚本中执行相同的操作呢?

Ini*_*ian 11

您可以使用bash command substitution跨系统的可移植性,而不是使用特定于变体的命令.

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

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

将它包装在更实用的shell函数中

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

$ repeatChar str 10
strstrstrstrstrstrstrstrstrstr
Run Code Online (Sandbox Code Playgroud)

  • 使用`printf -v myString'%*s'"$ count"`而不是`myString = $(...)`.并使用`local`将变量标记为本地(或删除局部变量并直接使用参数). (4认同)

小智 6

你可以简单地使用循环

$ for i in {1..4}; do echo -n 'm'; done
mmmm
Run Code Online (Sandbox Code Playgroud)


Oha*_*tan 5

那会做:

printf 'f'; printf 'o%.0s' {1..2}; echo
Run Code Online (Sandbox Code Playgroud)

在这里查看“乘法”部分的解释。