我怎么用echo来做呢?
perl -E 'say "=" x 100'
我怎么用echo来做呢?
perl -E 'say "=" x 100'
当前回答
另一种选择是使用GNU seq并删除它生成的所有数字和换行:
seq -f'#%.0f' 100 | tr -d '\n0123456789'
这个命令打印#字符100次。
其他回答
我怎么用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}
}
没有简单的办法。使用printf和substitution避免循环。
str=$(printf "%40s")
echo ${str// /rep}
# echoes "rep" 40 times.
另一种表示任意字符串重复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序列扩展为重复字符。
问题是关于如何使用echo:
echo -e ''$_{1..100}'\b='
这将与perl -E 'say "=" x 100'完全相同,但只使用echo。