How can I repeat a character in bash?

2019-01-02 14:25发布

How could I do this with echo?

perl -E 'say "=" x 100'

标签: bash shell echo
20条回答
余生请多指教
2楼-- · 2019-01-02 15:14

This is the longer version of what Eliah Kagan was espousing:

while [ $(( i-- )) -gt 0 ]; do echo -n "  "; done

Of course you can use printf for that as well, but not really to my liking:

printf "%$(( i*2 ))s"

This version is Dash compatible:

until [ $(( i=i-1 )) -lt 0 ]; do echo -n "  "; done

with i being the initial number.

查看更多
浅入江南
3楼-- · 2019-01-02 15:17

Python is ubiquitous and works the same everywhere.

python -c "import sys; print('*' * int(sys.argv[1]))" "=" 100

Character and count are passed as separate parameters.

查看更多
后来的你喜欢了谁
4楼-- · 2019-01-02 15:19

I've just found a seriously easy way to do this using seq:

UPDATE: This works on the BSD seq that comes with OS X. YMMV with other versions

seq  -f "#" -s '' 10

Will print '#' 10 times, like this:

##########
  • -f "#" sets the format string to ignore the numbers and just print # for each one.
  • -s '' sets the separator to an empty string to remove the newlines that seq inserts between each number
  • The spaces after -f and -s seem to be important.

EDIT: Here it is in a handy function...

repeat () {
    seq  -f $1 -s '' $2; echo
}

Which you can call like this...

repeat "#" 10

NOTE: If you're repeating # then the quotes are important!

查看更多
时光乱了年华
5楼-- · 2019-01-02 15:19

If you want POSIX-compliance and consistency across different implementations of echo and printf, and/or shells other than just 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)

...will produce the same output as perl -E 'say "=" x 100' just about everywhere.

查看更多
妖精总统
6楼-- · 2019-01-02 15:19

In bash 3.0 or higher

for i in {1..100};do echo -n =;done
查看更多
人气声优
7楼-- · 2019-01-02 15:22

No easy way. But for example:

seq -s= 100|tr -d '[:digit:]'

Or maybe a standard-conforming way:

printf %100s |tr " " "="

There's also a tput rep, but as for my terminals at hand (xterm and linux) they don't seem to support it:)

查看更多
登录 后发表回答