我怎么用echo来做呢?
perl -E 'say "=" x 100'
我怎么用echo来做呢?
perl -E 'say "=" x 100'
当前回答
另一种表示任意字符串重复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的变量值):
n=100
seq 1 $n | xargs -I {} printf =
没有简单的方法。但是举个例子:
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),它们似乎不支持它:)
如果你想重复一个字符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========
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
有不止一种方法。
使用循环:
大括号展开可用于整型字面值: 对于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 " " "="