我怎么用echo来做呢?

perl -E 'say "=" x 100'

当前回答

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

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

其他回答

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

双破折号——表示“命令行标志的结束”,所以不要试图解析命令行选项后面的内容。

如果你想打印破折号字符,而不是=字符,多次,不包括双破折号-这是你会得到的:

$ printf '-%.0s' {1..100}
bash: printf: -%: invalid option
printf: usage: printf [-v var] format [arguments]

为什么不创建这样的一行函数呢:

function repeat() { num="${2:-100}"; printf -- "$1%.0s" $(seq 1 $num); }

然后,你可以这样调用它:

$ repeat -
----------------------------------------------------------------------------------------------------

或者像这样:

$ repeat =
====================================================================================================

或者像这样:

$ repeat '*' 8
********

下面是我在linux中用来在屏幕上打印一行字符的方法(基于终端/屏幕宽度)

在屏幕上输入“=”:

printf '=%.0s' $(seq 1 $(tput cols))

解释:

打印等号的次数与给定序列相同:

printf '=%.0s' #sequence

使用命令的输出(这是bash的一个叫做命令替换的特性):

$(example_command)

给出一个序列,我以1到20为例。在最后一个命令中,使用tput命令代替20:

seq 1 20

给出终端中当前使用的列数:

tput cols

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

如果你想重复一个字符n次,n是一个变量的次数,这取决于,比如说,字符串的长度,你可以这样做:

#!/bin/bash
vari='AB'
n=$(expr 10 - length $vari)
echo 'vari equals.............................: '$vari
echo 'Up to 10 positions I must fill with.....: '$n' equal signs'
echo $vari$(perl -E 'say "=" x '$n)

它显示:

vari equals.............................: AB  
Up to 10 positions I must fill with.....: 8 equal signs  
AB========  

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

$((COLUMNS/2))

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