我怎么用echo来做呢?

perl -E 'say "=" x 100'

当前回答

我怎么用echo来做呢?

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

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

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

其他回答

一种纯粹的Bash方式,没有eval,没有subshell,没有外部工具,没有大括号展开(即,你可以在变量中重复数字):

如果给你一个变量n,它展开为一个(非负的)数字和一个变量模式,例如,

$ n=5
$ pattern=hello
$ printf -v output '%*s' "$n"
$ output=${output// /$pattern}
$ echo "$output"
hellohellohellohellohello

你可以用它来创建一个函数:

repeat() {
    # $1=number of patterns to repeat
    # $2=pattern
    # $3=output variable name
    local tmp
    printf -v tmp '%*s' "$1"
    printf -v "$3" '%s' "${tmp// /$2}"
}

这套:

$ repeat 5 hello output
$ echo "$output"
hellohellohellohellohello

对于这个小技巧,我们经常使用printf:

-v varname: instead of printing to standard output, printf will put the content of the formatted string in variable varname. '%*s': printf will use the argument to print the corresponding number of spaces. E.g., printf '%*s' 42 will print 42 spaces. Finally, when we have the wanted number of spaces in our variable, we use a parameter expansion to replace all the spaces by our pattern: ${var// /$pattern} will expand to the expansion of var with all the spaces replaced by the expansion of $pattern.


你也可以通过间接展开来去掉repeat函数中的tmp变量:

repeat() {
    # $1=number of patterns to repeat
    # $2=pattern
    # $3=output variable name
    printf -v "$3" '%*s' "$1"
    printf -v "$3" '%s' "${!3// /$2}"
}

我刚刚发现了一个非常简单的方法来做到这一点使用seq:

更新:此功能适用于OS x附带的BSD序列。YMMV与其他版本

seq  -f "#" -s '' 10

将打印'#' 10次,如下所示:

##########

-f "#"设置格式字符串忽略数字,只输出#。 -s "将分隔符设置为空字符串,以删除seq在每个数字之间插入的换行符 -f和-s后面的空格似乎很重要。

编辑:这里是一个方便的功能…

repeat () {
    seq  -f $1 -s '' $2; echo
}

你可以这样叫它…

repeat "#" 10

注意:如果你重复使用#,那么引号就很重要!

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

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

这个命令打印#字符100次。

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
********

Python无处不在,在任何地方都能正常工作。

import sys;Print ('*' * int(sys.argv[1]))"" = " 100

Character和count作为单独的参数传递。