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?
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.
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.
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).
$() 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.
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
You could simply use loop
$ for i in {1..4}; do echo -n 'm'; done
mmmm
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With