我怎么用echo来做呢?

perl -E 'say "=" x 100'

当前回答

不是堆砌,而是另一种纯bash方法利用了数组的${//}替换:

$ arr=({1..100})
$ printf '%s' "${arr[@]/*/=}"
====================================================================================================

其他回答

不是堆砌,而是另一种纯bash方法利用了数组的${//}替换:

$ arr=({1..100})
$ printf '%s' "${arr[@]/*/=}"
====================================================================================================

另一种表示任意字符串重复n次:

优点:

使用POSIX shell工作。 输出可以赋值给一个变量。 重复任何字符串。 即使有很大的重复也非常快。

缺点:

需要Gnu核心Utils的yes命令。

#!/usr/bin/sh
to_repeat='='
repeat_count=80
yes "$to_repeat" | tr -d '\n' | head -c "$repeat_count"

使用ANSI终端和重复的US-ASCII字符。您可以使用ANSI CSI转义序列。这是重复一个汉字最快的方法。

#!/usr/bin/env bash

char='='
repeat_count=80
printf '%c\e[%db' "$char" "$repeat_count"

或静态:

打印一行80次=:

printf’= e [80b \ n '

限制:

不是所有的终端都理解repeat_char ANSI CSI序列。 只能重复US-ASCII或单字节ISO字符。 在最后一列重复停止,因此可以使用较大的值来填充整行,而不管终端宽度如何。 重复只是为了显示。将输出捕获到shell变量中不会将repeat_char ANSI CSI序列扩展为重复字符。

另一个使用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

你可以使用:

printf '=%.0s' {1..100}

这是如何工作的:

Bash扩展{1..100},那么命令就变成:

printf '=%.0s' 1 2 3 4 ... 100

我已经将printf的格式设置为=%。这意味着无论给出什么参数,它总是打印一个=。因此它输出100 =s。

正如其他人所说,在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是要重复的文本。