在bash脚本中乘法字符串 [英] Multiplying strings in bash script
本文介绍了在bash脚本中乘法字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道,如果我在python中执行print ("f" + 2 * "o")
,则输出将为foo
.
I know that if I do print ("f" + 2 * "o")
in python the output will be foo
.
但是我如何在bash脚本中做同样的事情?
But how do I do the same thing in a bash script?
推荐答案
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
使用更有用的shell函数将其包装
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
这篇关于在bash脚本中乘法字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文