我怎么用echo来做呢?

perl -E 'say "=" x 100'

在bash 3.0或更高版本中

for i in {1..100};do echo -n =;done

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 " " "="

没有简单的方法。但是举个例子:

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),它们似乎不支持它:)


没有简单的办法。使用printf和substitution避免循环。

str=$(printf "%40s")
echo ${str// /rep}
# echoes "rep" 40 times.

你可以使用:

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

这是如何工作的:

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

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

我已经将printf的格式设置为=%。这意味着无论给出什么参数,它总是打印一个=。因此它输出100 =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))

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


这里有两种有趣的方法:

ubuntu@ubuntu:~$ yes = | head -10 | paste -s -d '' -
==========
ubuntu@ubuntu:~$ yes = | head -10 | tr -d "\n"
==========ubuntu@ubuntu:~$ 

注意这两个方法略有不同——粘贴方法以新行结束。tr方法没有。


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

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

seq  -f "#" -s '' 10

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

##########

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

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

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

你可以这样叫它…

repeat "#" 10

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


#!/usr/bin/awk -f
BEGIN {
  OFS = "="
  NF = 100
  print
}

Or

#!/usr/bin/awk -f
BEGIN {
  while (z++ < 100) printf "="
}

例子


一种纯粹的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}"
}

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


repeat() {
    # $1=number of patterns to repeat
    # $2=pattern
    printf -v "TEMP" '%*s' "$1"
    echo ${TEMP// /$2}
}

如果你想在echo和printf的不同实现之间遵循posix并保持一致性,和/或shell而不仅仅是bash:

seq(){ n=$1; while [ $n -le $2 ]; do echo $n; n=$((n+1)); done ;} # If you don't have it.

echo $(for each in $(seq 1 100); do printf "="; done)

...将在所有地方产生与perl -E 'say "=" x 100'相同的输出。


这是以利亚·卡根所支持的观点的长版本:

while [ $(( i-- )) -gt 0 ]; do echo -n "  "; done

当然,你也可以使用printf,但不是我喜欢的:

printf "%$(( i*2 ))s"

这个版本与Dash兼容:

until [ $(( i=i-1 )) -lt 0 ]; do echo -n "  "; done

I是初始数。


向@gniourf_gniourf致敬。

注意:这个答案并没有回答最初的问题,而是通过比较性能来补充现有的有用答案。

解决方案只在执行速度方面进行比较-内存需求没有考虑在内(它们在不同的解决方案中有所不同,并且可能与大量重复计数有关)。

简介:

If your repeat count is small, say up to around 100, it's worth going with the Bash-only solutions, as the startup cost of external utilities matters, especially Perl's. Pragmatically speaking, however, if you only need one instance of repeating characters, all existing solutions may be fine. With large repeat counts, use external utilities, as they'll be much faster. In particular, avoid Bash's global substring replacement with large strings (e.g., ${var// /=}), as it is prohibitively slow.

以下是在一台配有3.2 GHz Intel酷睿i5 CPU和Fusion Drive的2012年末iMac上进行的计时,运行OSX 10.10.4和bash 3.2.57,是1000次运行的平均值。

条目如下:

按执行时间升序列出(最快的先) 前缀: 米……一个潜在的多字符解决方案 年代……单字符解决方案 P…posix兼容的解决方案 接下来是对解决方案的简要描述 以原始答案的作者的名字作为后缀


小重复计数:100

[M, P] printf %.s= [dogbane]:                           0.0002
[M   ] printf + bash global substr. replacement [Tim]:  0.0005
[M   ] echo -n - brace expansion loop [eugene y]:       0.0007
[M   ] echo -n - arithmetic loop [Eliah Kagan]:         0.0013
[M   ] seq -f [Sam Salisbury]:                          0.0016
[M   ] jot -b [Stefan Ludwig]:                          0.0016
[M   ] awk - $(count+1)="=" [Steven Penny (variant)]:   0.0019
[M, P] awk - while loop [Steven Penny]:                 0.0019
[S   ] printf + tr [user332325]:                        0.0021
[S   ] head + tr [eugene y]:                            0.0021
[S, P] dd + tr [mklement0]:                             0.0021
[M   ] printf + sed [user332325 (comment)]:             0.0021
[M   ] mawk - $(count+1)="=" [Steven Penny (variant)]:  0.0025
[M, P] mawk - while loop [Steven Penny]:                0.0026
[M   ] gawk - $(count+1)="=" [Steven Penny (variant)]:  0.0028
[M, P] gawk - while loop [Steven Penny]:                0.0028
[M   ] yes + head + tr [Digital Trauma]:                0.0029
[M   ] Perl [sid_com]:                                  0.0059

只有bash的解决方案领先的包-但只有重复计数这么小!(见下文)。 外部实用程序的启动成本在这里很重要,特别是Perl的启动成本。如果必须在循环中调用它——每次迭代中重复次数很少——请避免使用multi-utility、awk和perl解决方案。


大重复计数:1000000(100万)

[M   ] Perl [sid_com]:                                  0.0067
[M   ] mawk - $(count+1)="=" [Steven Penny (variant)]:  0.0254
[M   ] gawk - $(count+1)="=" [Steven Penny (variant)]:  0.0599
[S   ] head + tr [eugene y]:                            0.1143
[S, P] dd + tr [mklement0]:                             0.1144
[S   ] printf + tr [user332325]:                        0.1164
[M, P] mawk - while loop [Steven Penny]:                0.1434
[M   ] seq -f [Sam Salisbury]:                          0.1452
[M   ] jot -b [Stefan Ludwig]:                          0.1690
[M   ] printf + sed [user332325 (comment)]:             0.1735
[M   ] yes + head + tr [Digital Trauma]:                0.1883
[M, P] gawk - while loop [Steven Penny]:                0.2493
[M   ] awk - $(count+1)="=" [Steven Penny (variant)]:   0.2614
[M, P] awk - while loop [Steven Penny]:                 0.3211
[M, P] printf %.s= [dogbane]:                           2.4565
[M   ] echo -n - brace expansion loop [eugene y]:       7.5877
[M   ] echo -n - arithmetic loop [Eliah Kagan]:         13.5426
[M   ] printf + bash global substr. replacement [Tim]:  n/a

The Perl solution from the question is by far the fastest. Bash's global string-replacement (${foo// /=}) is inexplicably excruciatingly slow with large strings, and has been taken out of the running (took around 50 minutes(!) in Bash 4.3.30, and even longer in Bash 3.2.57 - I never waited for it to finish). Bash loops are slow, and arithmetic loops ((( i= 0; ... ))) are slower than brace-expanded ones ({1..n}) - though arithmetic loops are more memory-efficient. awk refers to BSD awk (as also found on OSX) - it's noticeably slower than gawk (GNU Awk) and especially mawk. Note that with large counts and multi-char. strings, memory consumption can become a consideration - the approaches differ in that respect.


下面是生成上述代码的Bash脚本(testrepeat)。 它有两个参数:

字符重复计数 可选地,要执行的测试运行的数量,并从中计算平均时间

换句话说:上面的时间是用testrepeat 100 1000和testrepeat 1000000 1000得到的

#!/usr/bin/env bash

title() { printf '%s:\t' "$1"; }

TIMEFORMAT=$'%6Rs'

# The number of repetitions of the input chars. to produce
COUNT_REPETITIONS=${1?Arguments: <charRepeatCount> [<testRunCount>]}

# The number of test runs to perform to derive the average timing from.
COUNT_RUNS=${2:-1}

# Discard the (stdout) output generated by default.
# If you want to check the results, replace '/dev/null' on the following
# line with a prefix path to which a running index starting with 1 will
# be appended for each test run; e.g., outFilePrefix='outfile', which
# will produce outfile1, outfile2, ...
outFilePrefix=/dev/null

{

  outFile=$outFilePrefix
  ndx=0

  title '[M, P] printf %.s= [dogbane]'
  [[ $outFile != '/dev/null' ]] && outFile="$outFilePrefix$((++ndx))"
  # !! In order to use brace expansion with a variable, we must use `eval`.
  eval "
  time for (( n = 0; n < COUNT_RUNS; n++ )); do 
    printf '%.s=' {1..$COUNT_REPETITIONS} >"$outFile"
  done"

  title '[M   ] echo -n - arithmetic loop [Eliah Kagan]'
  [[ $outFile != '/dev/null' ]] && outFile="$outFilePrefix$((++ndx))"
  time for (( n = 0; n < COUNT_RUNS; n++ )); do 
    for ((i=0; i<COUNT_REPETITIONS; ++i)); do echo -n =; done >"$outFile"
  done


  title '[M   ] echo -n - brace expansion loop [eugene y]'
  [[ $outFile != '/dev/null' ]] && outFile="$outFilePrefix$((++ndx))"
  # !! In order to use brace expansion with a variable, we must use `eval`.
  eval "
  time for (( n = 0; n < COUNT_RUNS; n++ )); do 
    for i in {1..$COUNT_REPETITIONS}; do echo -n =; done >"$outFile"
  done
  "

  title '[M   ] printf + sed [user332325 (comment)]'
  [[ $outFile != '/dev/null' ]] && outFile="$outFilePrefix$((++ndx))"
  time for (( n = 0; n < COUNT_RUNS; n++ )); do 
    printf "%${COUNT_REPETITIONS}s" | sed 's/ /=/g' >"$outFile"
  done


  title '[S   ] printf + tr [user332325]'
  [[ $outFile != '/dev/null' ]] && outFile="$outFilePrefix$((++ndx))"
  time for (( n = 0; n < COUNT_RUNS; n++ )); do 
    printf "%${COUNT_REPETITIONS}s" | tr ' ' '='  >"$outFile"
  done


  title '[S   ] head + tr [eugene y]'
  [[ $outFile != '/dev/null' ]] && outFile="$outFilePrefix$((++ndx))"
  time for (( n = 0; n < COUNT_RUNS; n++ )); do 
    head -c $COUNT_REPETITIONS < /dev/zero | tr '\0' '=' >"$outFile"
  done


  title '[M   ] seq -f [Sam Salisbury]'
  [[ $outFile != '/dev/null' ]] && outFile="$outFilePrefix$((++ndx))"
  time for (( n = 0; n < COUNT_RUNS; n++ )); do 
    seq -f '=' -s '' $COUNT_REPETITIONS >"$outFile"
  done


  title '[M   ] jot -b [Stefan Ludwig]'
  [[ $outFile != '/dev/null' ]] && outFile="$outFilePrefix$((++ndx))"
  time for (( n = 0; n < COUNT_RUNS; n++ )); do 
    jot -s '' -b '=' $COUNT_REPETITIONS >"$outFile"
  done


  title '[M   ] yes + head + tr [Digital Trauma]'
  [[ $outFile != '/dev/null' ]] && outFile="$outFilePrefix$((++ndx))"
  time for (( n = 0; n < COUNT_RUNS; n++ )); do 
    yes = | head -$COUNT_REPETITIONS | tr -d '\n'  >"$outFile"
  done

  title '[M   ] Perl [sid_com]'
  [[ $outFile != '/dev/null' ]] && outFile="$outFilePrefix$((++ndx))"
  time for (( n = 0; n < COUNT_RUNS; n++ )); do 
    perl -e "print \"=\" x $COUNT_REPETITIONS" >"$outFile"
  done

  title '[S, P] dd + tr [mklement0]'
  [[ $outFile != '/dev/null' ]] && outFile="$outFilePrefix$((++ndx))"
  time for (( n = 0; n < COUNT_RUNS; n++ )); do 
    dd if=/dev/zero bs=$COUNT_REPETITIONS count=1 2>/dev/null | tr '\0' "=" >"$outFile"
  done

  # !! On OSX, awk is BSD awk, and mawk and gawk were installed later.
  # !! On Linux systems, awk may refer to either mawk or gawk.
  for awkBin in awk mawk gawk; do
    if [[ -x $(command -v $awkBin) ]]; then

      title "[M   ] $awkBin"' - $(count+1)="=" [Steven Penny (variant)]'
      [[ $outFile != '/dev/null' ]] && outFile="$outFilePrefix$((++ndx))"
      time for (( n = 0; n < COUNT_RUNS; n++ )); do 
        $awkBin -v count=$COUNT_REPETITIONS 'BEGIN { OFS="="; $(count+1)=""; print }' >"$outFile"
      done

      title "[M, P] $awkBin"' - while loop [Steven Penny]'
      [[ $outFile != '/dev/null' ]] && outFile="$outFilePrefix$((++ndx))"
      time for (( n = 0; n < COUNT_RUNS; n++ )); do 
        $awkBin -v count=$COUNT_REPETITIONS 'BEGIN { while (i++ < count) printf "=" }' >"$outFile"
      done

    fi
  done

  title '[M   ] printf + bash global substr. replacement [Tim]'
  [[ $outFile != '/dev/null' ]] && outFile="$outFilePrefix$((++ndx))"
  # !! In Bash 4.3.30 a single run with repeat count of 1 million took almost
  # !! 50 *minutes*(!) to complete; n Bash 3.2.57 it's seemingly even slower -
  # !! didn't wait for it to finish.
  # !! Thus, this test is skipped for counts that are likely to be much slower
  # !! than the other tests.
  skip=0
  [[ $BASH_VERSINFO -le 3 && COUNT_REPETITIONS -gt 1000 ]] && skip=1
  [[ $BASH_VERSINFO -eq 4 && COUNT_REPETITIONS -gt 10000 ]] && skip=1
  if (( skip )); then
    echo 'n/a' >&2
  else
    time for (( n = 0; n < COUNT_RUNS; n++ )); do 
      { printf -v t "%${COUNT_REPETITIONS}s" '='; printf %s "${t// /=}"; } >"$outFile"
    done
  fi
} 2>&1 | 
 sort -t$'\t' -k2,2n | 
   awk -F $'\t' -v count=$COUNT_RUNS '{ 
    printf "%s\t", $1; 
    if ($2 ~ "^n/a") { print $2 } else { printf "%.4f\n", $2 / count }}' |
     column -s$'\t' -t

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

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

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


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


最简单的方法是在csh/tcsh中使用这一行代码:

printf "%50s\n" '' | tr '[:blank:]' '[=]'


问题是关于如何使用echo:

echo -e ''$_{1..100}'\b='

这将与perl -E 'say "=" x 100'完全相同,但只使用echo。


我怎么用echo来做呢?

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

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

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


我的答案有点复杂,可能并不完美,但对于那些希望输出大数字的人来说,我能够在3秒内完成大约1000万。

repeatString(){
    # argument 1: The string to print
    # argument 2: The number of times to print
    stringToPrint=$1
    length=$2

    # Find the largest integer value of x in 2^x=(number of times to repeat) using logarithms
    power=`echo "l(${length})/l(2)" | bc -l`
    power=`echo "scale=0; ${power}/1" | bc`

    # Get the difference between the length and 2^x
    diff=`echo "${length} - 2^${power}" | bc`

    # Double the string length to the power of x
    for i in `seq "${power}"`; do 
        stringToPrint="${stringToPrint}${stringToPrint}"
    done

    #Since we know that the string is now at least bigger than half the total, grab however many more we need and add it to the string.
    stringToPrint="${stringToPrint}${stringToPrint:0:${diff}}"
    echo ${stringToPrint}
}

最简单的方法是在bash中使用这一行代码:

seq 10 | xargs -n 1 | xargs -I {} echo -n  ===\>;echo


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

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

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

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

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


大多数现有的解决方案都依赖于{1..shell的10}语法支持,这是bash和zsh特定的,并且不能在tcsh或OpenBSD的ksh和大多数非bash sh中工作。

以下代码适用于OS X和所有*BSD系统;实际上,它可以用来生成各种类型装饰空间的整体矩阵:

$ printf '=%.0s' `jot 64` | fold -16
================
================
================
================$ 

遗憾的是,我们没有得到一个尾随换行符;这可以通过在折叠后额外的printf '\n'来修复:

$ printf "=%.0s" `jot 64` | fold -16 ; printf "\n"
================
================
================
================
$ 

引用:

http://mdoc.su/-/printf.1 http://mdoc.su/-/jot.1 http://mdoc.su/-/fold.1


另一种表示任意字符串重复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序列扩展为重复字符。


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

在屏幕上输入“=”:

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

解释:

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

printf '=%.0s' #sequence

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

$(example_command)

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

seq 1 20

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

tput cols

我的建议(接受n的变量值):

n=100
seq 1 $n | xargs -I {} printf =

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

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

n=5; chr='x'; chr_string='';
for (( i=0; $i<$n; i++ ))
do
    chr_string=$chr_string$chr
done
echo -n "$chr_string"

适用于…… N =整数(包括0和负数)。 Chr =可打印和空白(空格和制表符)。


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

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

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

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