我怎么用echo来做呢?
perl -E 'say "=" x 100'
我怎么用echo来做呢?
perl -E 'say "=" x 100'
当前回答
另一个使用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
其他回答
没有简单的办法。使用printf和substitution避免循环。
str=$(printf "%40s")
echo ${str// /rep}
# echoes "rep" 40 times.
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 =可打印和空白(空格和制表符)。
for i in {1..100}
do
echo -n '='
done
echo
我的答案有点复杂,可能并不完美,但对于那些希望输出大数字的人来说,我能够在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}
}
我怎么用echo来做呢?
如果echo后面跟着sed,你可以用echo来实现:
echo | sed -r ':a s/^(.*)$/=\1/; /^={100}$/q; ba'
实际上,这个回声在这里是不必要的。