我怎么用echo来做呢?
perl -E 'say "=" x 100'
我怎么用echo来做呢?
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
其他回答
你可以使用:
printf '=%.0s' {1..100}
这是如何工作的:
Bash扩展{1..100},那么命令就变成:
printf '=%.0s' 1 2 3 4 ... 100
我已经将printf的格式设置为=%。这意味着无论给出什么参数,它总是打印一个=。因此它输出100 =s。
repeat() {
# $1=number of patterns to repeat
# $2=pattern
printf -v "TEMP" '%*s' "$1"
echo ${TEMP// /$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序列扩展为重复字符。
在bash 3.0或更高版本中
for i in {1..100};do echo -n =;done
大多数现有的解决方案都依赖于{1..shell的10}语法支持,这是bash和zsh特定的,并且不能在tcsh或OpenBSD的ksh和大多数非bash sh中工作。
以下代码适用于OS X和所有*BSD系统;实际上,它可以用来生成各种类型装饰空间的整体矩阵:
$ printf '=%.0s' `jot 64` | fold -16
================
================
================
================$
遗憾的是,我们没有得到一个尾随换行符;这可以通过在折叠后额外的printf '\n'来修复:
$ printf "=%.0s" `jot 64` | fold -16 ; printf "\n"
================
================
================
================
$
引用:
http://mdoc.su/-/printf.1 http://mdoc.su/-/jot.1 http://mdoc.su/-/fold.1