我怎么用echo来做呢?
perl -E 'say "=" x 100'
我怎么用echo来做呢?
perl -E 'say "=" x 100'
当前回答
printf -- '=%.0s' {1..100}
双破折号——表示“命令行标志的结束”,所以不要试图解析命令行选项后面的内容。
如果你想打印破折号字符,而不是=字符,多次,不包括双破折号-这是你会得到的:
$ printf '-%.0s' {1..100}
bash: printf: -%: invalid option
printf: usage: printf [-v var] format [arguments]
为什么不创建这样的一行函数呢:
function repeat() { num="${2:-100}"; printf -- "$1%.0s" $(seq 1 $num); }
然后,你可以这样调用它:
$ repeat -
----------------------------------------------------------------------------------------------------
或者像这样:
$ repeat =
====================================================================================================
或者像这样:
$ repeat '*' 8
********
其他回答
不是堆砌,而是另一种纯bash方法利用了数组的${//}替换:
$ arr=({1..100})
$ printf '%s' "${arr[@]/*/=}"
====================================================================================================
下面是我在linux中用来在屏幕上打印一行字符的方法(基于终端/屏幕宽度)
在屏幕上输入“=”:
printf '=%.0s' $(seq 1 $(tput cols))
解释:
打印等号的次数与给定序列相同:
printf '=%.0s' #sequence
使用命令的输出(这是bash的一个叫做命令替换的特性):
$(example_command)
给出一个序列,我以1到20为例。在最后一个命令中,使用tput命令代替20:
seq 1 20
给出终端中当前使用的列数:
tput cols
有不止一种方法。
使用循环:
大括号展开可用于整型字面值: 对于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 " " "="
如果你想在echo和printf的不同实现之间遵循posix并保持一致性,和/或shell而不仅仅是bash:
seq(){ n=$1; while [ $n -le $2 ]; do echo $n; n=$((n+1)); done ;} # If you don't have it.
echo $(for each in $(seq 1 100); do printf "="; done)
...将在所有地方产生与perl -E 'say "=" x 100'相同的输出。
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