我怎么用echo来做呢?

perl -E 'say "=" x 100'

当前回答

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

$((COLUMNS/2))

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

其他回答

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

有不止一种方法。

使用循环:

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

另一个使用printf和tr的bash解决方案

nb。在开始之前:

我们需要另一个答案吗?可能不会。 答案已经在这里了吗?看不见,就这样。

使用printf的前导零填充特性,并使用tr转换零。这避免了任何{1..N}发电机:

$ printf '%040s' | tr '0' '='
========================================

设置宽度为'N'字符,并自定义打印的字符:

#!/usr/bin/env bash
N=40
C='-'
printf "%0${N}s" | tr '0' "${C}"

对于大N,这比生成器的性能要好得多;在我的机器上(bash 3.2.57):

$ time printf '=%.0s' {1..1000000}         real: 0m2.580s
$ time printf '%01000000s' | tr '0' '='    real: 0m0.577s

没有简单的方法。但是举个例子:

seq -s= 100|tr -d '[:digit:]'
# Editor's note: This requires BSD seq, and breaks with GNU seq (see comments)

或者是一种符合标准的方式:

printf %100s |tr " " "="

还有一个tput代表,但对于我手头的终端(xterm和linux),它们似乎不支持它:)

稍微长一点的版本,但如果你出于某种原因必须使用纯Bash,你可以使用一个带增量变量的while循环:

n=0; while [ $n -lt 100 ]; do n=$((n+1)); echo -n '='; done