我怎么用echo来做呢?

perl -E 'say "=" x 100'

当前回答

正如其他人所说,在bash中,大括号展开先于参数展开,因此{m,n}范围只能包含字面量。Seq和jot提供了干净的解决方案,但不能完全从一个系统移植到另一个系统,即使在每个系统上使用相同的shell。(尽管seq越来越多;例如,在FreeBSD 9.3和更高版本中。)eval和其他形式的间接方法总是有效的,但有些不优雅。

幸运的是,bash支持c风格的for循环(只支持算术表达式)。这里有一个简洁的“纯bash”方法:

repecho() { for ((i=0; i<$1; ++i)); do echo -n "$2"; done; echo; }

这将重复次数作为第一个参数,将要重复的字符串(如问题描述中所示,可以是单个字符)作为第二个参数。Repecho 7b输出BBBBBBB(以换行符结束)。

Dennis Williamson四年前在他关于在shell脚本中创建重复字符字符串的出色回答中给出了这个解决方案。我的函数体与代码略有不同:

Since the focus here is on repeating a single character and the shell is bash, it's probably safe to use echo instead of printf. And I read the problem description in this question as expressing a preference to print with echo. The above function definition works in bash and ksh93. Although printf is more portable (and should usually be used for this sort of thing), echo's syntax is arguably more readable. Some shells' echo builtins interpret - by itself as an option--even though the usual meaning of -, to use stdin for input, is nonsensical for echo. zsh does this. And there definitely exist echos that don't recognize -n, as it is not standard. (Many Bourne-style shells don't accept C-style for loops at all, thus their echo behavior needn't be considered..) Here the task is to print the sequence; there, it was to assign it to a variable.

如果$n是你想要的重复次数,你不需要重用它,你想要更短的东西:

while ((n--)); do echo -n "$s"; done; echo

N必须是一个变量——这种方法不适用于位置参数。$s是要重复的文本。

其他回答

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

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

这个命令打印#字符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

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

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

我怎么用echo来做呢?

如果echo后面跟着sed,你可以用echo来实现:

echo | sed -r ':a s/^(.*)$/=\1/; /^={100}$/q; ba'

实际上,这个回声在这里是不必要的。

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

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