我怎么用echo来做呢?

perl -E 'say "=" x 100'

当前回答

没有简单的办法。使用printf和substitution避免循环。

str=$(printf "%40s")
echo ${str// /rep}
# echoes "rep" 40 times.

其他回答

我猜这个问题的最初目的是仅用shell的内置命令来完成这个任务。因此,for循环和printfs是合法的,而下面的rep、perl和jot则不是。但是,下面的命令

$((COLUMNS/2))

例如,打印的窗户完全线 \/\/\/\/\/\/\/\/\/\/\/\/

有不止一种方法。

使用循环:

大括号展开可用于整型字面值: 对于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 " " "="

我的答案有点复杂,可能并不完美,但对于那些希望输出大数字的人来说,我能够在3秒内完成大约1000万。

repeatString(){
    # argument 1: The string to print
    # argument 2: The number of times to print
    stringToPrint=$1
    length=$2

    # Find the largest integer value of x in 2^x=(number of times to repeat) using logarithms
    power=`echo "l(${length})/l(2)" | bc -l`
    power=`echo "scale=0; ${power}/1" | bc`

    # Get the difference between the length and 2^x
    diff=`echo "${length} - 2^${power}" | bc`

    # Double the string length to the power of x
    for i in `seq "${power}"`; do 
        stringToPrint="${stringToPrint}${stringToPrint}"
    done

    #Since we know that the string is now at least bigger than half the total, grab however many more we need and add it to the string.
    stringToPrint="${stringToPrint}${stringToPrint:0:${diff}}"
    echo ${stringToPrint}
}

建议的Python解决方案的更优雅的替代方案可能是:

python -c 'print "="*(1000)'

另一种选择是使用GNU seq并删除它生成的所有数字和换行:

seq -f'#%.0f' 100 | tr -d '\n0123456789'

这个命令打印#字符100次。