我怎么用echo来做呢?
perl -E 'say "=" x 100'
我怎么用echo来做呢?
perl -E 'say "=" x 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序列扩展为重复字符。
我的答案有点复杂,可能并不完美,但对于那些希望输出大数字的人来说,我能够在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}
}
另一个使用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
#!/usr/bin/awk -f
BEGIN {
OFS = "="
NF = 100
print
}
Or
#!/usr/bin/awk -f
BEGIN {
while (z++ < 100) printf "="
}
例子
没有简单的办法。使用printf和substitution避免循环。
str=$(printf "%40s")
echo ${str// /rep}
# echoes "rep" 40 times.