我怎么用echo来做呢?
perl -E 'say "=" x 100'
我怎么用echo来做呢?
perl -E 'say "=" x 100'
当前回答
这里有两种有趣的方法:
ubuntu@ubuntu:~$ yes = | head -10 | paste -s -d '' - ========== ubuntu@ubuntu:~$ yes = | head -10 | tr -d "\n" ==========ubuntu@ubuntu:~$
注意这两个方法略有不同——粘贴方法以新行结束。tr方法没有。
其他回答
没有简单的方法。但是举个例子:
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),它们似乎不支持它:)
for i in {1..100}
do
echo -n '='
done
echo
有不止一种方法。
使用循环:
大括号展开可用于整型字面值: 对于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
正如其他人所说,在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是要重复的文本。