我怎么用echo来做呢?
perl -E 'say "=" x 100'
我怎么用echo来做呢?
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是初始数。
其他回答
在bash 3.0或更高版本中
for i in {1..100};do echo -n =;done
一种纯粹的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}"
}
另一种表示任意字符串重复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序列扩展为重复字符。
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 =可打印和空白(空格和制表符)。
另一种选择是使用GNU seq并删除它生成的所有数字和换行:
seq -f'#%.0f' 100 | tr -d '\n0123456789'
这个命令打印#字符100次。