Bash:重复字符可变次数
Bash: repeat character a variable number of times
根据以下问题和反思:
https://unix.stackexchange.com/questions/188658/writing-a-character-n-times-using-the-printf-command
和
How can I repeat a character in bash?
我想了解如何为 character/string 参数化重复值。例如,以下内容非常有效:
printf " ,\n%0.s" {1..5}
但是,如果我想参数化“5”,请说:
num=5
我似乎无法获得正确的扩展来完成这项工作。例如:
printf " ,\n%0.s" {1..$((num))}
失败。
任何 thoughts/ideas 都将是最受欢迎的 - 我认为有一种方法可以做到这一点而不必求助于 perl 或 awk 所以只是好奇是否有可能。
谢谢!
您可以使用seq
num=20;
printf '\n%.0s' $(seq $num)
如果您可以将命令构建为一个字符串——带有您想要的所有参数扩展——那么您就可以对其进行评估。这会打印 X num
次:
num=10
eval $(echo printf '"X%0.s"' {1..$num})
略有不同的方法
$ repeat() {
local str= n= spaces
printf -v spaces "%*s" $n " " # create a string of spaces $n chars long
printf "%s" "${spaces// /$str}" # substitute each space with the requested string
}
$ repeat '!' 10
!!!!!!!!!! # <= no newline
$ repeat $' ,\n' 5
,
,
,
,
,
根据以下问题和反思:
https://unix.stackexchange.com/questions/188658/writing-a-character-n-times-using-the-printf-command
和
How can I repeat a character in bash?
我想了解如何为 character/string 参数化重复值。例如,以下内容非常有效:
printf " ,\n%0.s" {1..5}
但是,如果我想参数化“5”,请说:
num=5
我似乎无法获得正确的扩展来完成这项工作。例如:
printf " ,\n%0.s" {1..$((num))}
失败。
任何 thoughts/ideas 都将是最受欢迎的 - 我认为有一种方法可以做到这一点而不必求助于 perl 或 awk 所以只是好奇是否有可能。
谢谢!
您可以使用seq
num=20;
printf '\n%.0s' $(seq $num)
如果您可以将命令构建为一个字符串——带有您想要的所有参数扩展——那么您就可以对其进行评估。这会打印 X num
次:
num=10
eval $(echo printf '"X%0.s"' {1..$num})
略有不同的方法
$ repeat() {
local str= n= spaces
printf -v spaces "%*s" $n " " # create a string of spaces $n chars long
printf "%s" "${spaces// /$str}" # substitute each space with the requested string
}
$ repeat '!' 10
!!!!!!!!!! # <= no newline
$ repeat $' ,\n' 5
,
,
,
,
,