我怎么用echo来做呢?
perl -E 'say "=" x 100'
我怎么用echo来做呢?
perl -E 'say "=" x 100'
当前回答
有不止一种方法。
使用循环:
大括号展开可用于整型字面值: 对于I在{1..100};执行echo -n =;完成 类c循环允许使用变量: 开始= 1 结束= 100 ((我= $开始;我< = $结束;我+ +));执行echo -n =;完成
使用内置的printf:
printf '=%.0s' {1..100}
在这里指定精度将截断字符串以适应指定的宽度(0)。当printf重用格式字符串以使用所有参数时,这将简单地打印"=" 100次。
使用head (printf, etc)和tr:
head -c 100 < /dev/zero | tr '\0' '='
printf %100s | tr " " "="
其他回答
建议的Python解决方案的更优雅的替代方案可能是:
python -c 'print "="*(1000)'
repeat() {
# $1=number of patterns to repeat
# $2=pattern
printf -v "TEMP" '%*s' "$1"
echo ${TEMP// /$2}
}
如果你想在echo和printf的不同实现之间遵循posix并保持一致性,和/或shell而不仅仅是bash:
seq(){ n=$1; while [ $n -le $2 ]; do echo $n; n=$((n+1)); done ;} # If you don't have it.
echo $(for each in $(seq 1 100); do printf "="; done)
...将在所有地方产生与perl -E 'say "=" x 100'相同的输出。
function repeatString()
{
local -r string="${1}"
local -r numberToRepeat="${2}"
if [[ "${string}" != '' && "${numberToRepeat}" =~ ^[1-9][0-9]*$ ]]
then
local -r result="$(printf "%${numberToRepeat}s")"
echo -e "${result// /${string}}"
fi
}
样本运行
$ repeatString 'a1' 10
a1a1a1a1a1a1a1a1a1a1
$ repeatString 'a1' 0
$ repeatString '' 10
参考库:https://github.com/gdbtek/linux-cookbooks/blob/master/libraries/util.bash
如果你想重复一个字符n次,n是一个变量的次数,这取决于,比如说,字符串的长度,你可以这样做:
#!/bin/bash
vari='AB'
n=$(expr 10 - length $vari)
echo 'vari equals.............................: '$vari
echo 'Up to 10 positions I must fill with.....: '$n' equal signs'
echo $vari$(perl -E 'say "=" x '$n)
它显示:
vari equals.............................: AB
Up to 10 positions I must fill with.....: 8 equal signs
AB========