bash 在bash脚本中乘以字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38868665/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Multiplying strings in bash script
提问by Jakob Kenda
I know that if I do print ("f" + 2 * "o")
in python the output will be foo
.
我知道如果我print ("f" + 2 * "o")
在 python 中做,输出将是foo
.
But how do I do the same thing in a bash script?
但是我如何在 bash 脚本中做同样的事情呢?
回答by Inian
You can use bash
command substitution
to be more portable across systems than to use a variant specific command.
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
Wrapping it up in a more usable shell-function
将它包装在一个更有用的 shell 函数中
repeatChar() {
local input=""
local count=""
printf -v myString "%s" "%${count}s"
printf '%s\n' "${myString// /$input}"
}
$ repeatChar str 10
strstrstrstrstrstrstrstrstrstr
回答by David C. Rankin
In bash you can use simple string indexing in a similar manner
在 bash 中,您可以以类似的方式使用简单的字符串索引
#!/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.
还有几个可以使用。
回答by ajay
You could simply use loop
你可以简单地使用循环
$ for i in {1..4}; do echo -n 'm'; done
mmmm
回答by Ohad Eytan
回答by Mukundhan
You can create a functionto loop a string for a specific countand use it in the loop you are executing with dynamic length. FYIa different version of oter answers.
您可以创建一个函数来循环特定计数的字符串,并在您以动态长度执行的循环中使用它。仅供参考,其他答案的不同版本。
line_break()
{
for i in `seq 0 ${count}`
do
echo -n "########################"
done
}
line_break 10
prints: ################
印刷: ################