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:00
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
}

Sample runs

$ repeatString 'a1' 10 
a1a1a1a1a1a1a1a1a1a1

$ repeatString 'a1' 0 

$ repeatString '' 10 

Reference lib at: https://github.com/gdbtek/linux-cookbooks/blob/master/libraries/util.bash

查看更多
栀子花@的思念
3楼-- · 2019-01-02 15:03

In case that you want to repeat a character n times being n a VARIABLE number of times depending on, say, the length of a string you can do:

#!/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)

It displays:

vari equals.............................: AB  
Up to 10 positions I must fill with.....: 8 equal signs  
AB========  
查看更多
唯独是你
4楼-- · 2019-01-02 15:05

There's more than one way to do it.

Using a loop:

  • Brace expansion can be used with integer literals:

    for i in {1..100}; do echo -n =; done    
    
  • A C-like loop allows the use of variables:

    start=1
    end=100
    for ((i=$start; i<=$end; i++)); do echo -n =; done
    

Using the printf builtin:

printf '=%.0s' {1..100}

Specifying a precision here truncates the string to fit the specified width (0). As printf reuses the format string to consume all of the arguments, this simply prints "=" 100 times.

Using head (printf, etc) and tr:

head -c 100 < /dev/zero | tr '\0' '='
printf %100s | tr " " "="
查看更多
一个人的天荒地老
5楼-- · 2019-01-02 15:06

I guess the original purpose of the question was to do this just with the shell's built-in commands. So for loops and printfs would be legitimate, while rep, perl, and also jot below would not. Still, the following command

jot -s "/" -b "\\" $((COLUMNS/2))

for instance, prints a window-wide line of \/\/\/\/\/\/\/\/\/\/\/\/

查看更多
不再属于我。
6楼-- · 2019-01-02 15:07

Simplest is to use this one-liner in csh/tcsh:

printf "%50s\n" '' | tr '[:blank:]' '[=]'

查看更多
只靠听说
7楼-- · 2019-01-02 15:08
repeat() {
    # $1=number of patterns to repeat
    # $2=pattern
    printf -v "TEMP" '%*s' "$1"
    echo ${TEMP// /$2}
}
查看更多
登录 后发表回答