Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiplying strings in bash script

I know that if I do print ("f" + 2 * "o") in python the output will be foo.

But how do I do the same thing in a bash script?

like image 311
Jakob Kenda Avatar asked Aug 10 '16 08:08

Jakob Kenda


People also ask

How do you multiply strings?

To (properly) multiply an string by an integer, you split the string into characters, repeat each character a number of times equal to the integer, and then stick the characters back together. If the integer is negative, we use its absolute value in the first step, and then reverse the string.

How do you multiply two numbers in a shell script?

Multiplication of two numbers using expr in shell script In shell, * represents all files in the current directory. So, in order to use * as a multiplication operator, we should escape it like \*. If we directly use * in expr, we will get error message.

Can we multiply string variable?

Multiplication. You can do some funny things with multiplication and strings. When you multiply a string by an integer, Python returns a new string. This new string is the original string, repeated X number of times (where X is the value of the integer).

What is $() in bash?

$() means: "first evaluate this, and then evaluate the rest of the line". Ex : echo $(pwd)/myFile.txt. will be interpreted as echo /my/path/myFile.txt. On the other hand ${} expands a variable.


2 Answers

You can use bash command substitution to be more portable across systems than to use a variant specific command.

$ myString=$(printf "%10s");echo ${myString// /m}           # echoes 'm' 10 times
mmmmmmmmmm

$ myString=$(printf "%10s");echo ${myString// /rep}         # echoes 'rep' 10 times
reprepreprepreprepreprepreprep

Wrapping it up in a more usable shell-function

repeatChar() {
    local input="$1"
    local count="$2"
    printf -v myString "%s" "%${count}s"
    printf '%s\n' "${myString// /$input}"
}

$ repeatChar str 10
strstrstrstrstrstrstrstrstrstr
like image 185
Inian Avatar answered Sep 22 '22 11:09

Inian


You could simply use loop

$ for i in {1..4}; do echo -n 'm'; done
mmmm
like image 43
ajay Avatar answered Sep 20 '22 11:09

ajay