n Bash, you can repeat a character ‘n’ times using the printf
command. The syntax for repeating a character ‘n’ times is as follows:
printf "%*s" n character
Where:
- n is the number of times you want to repeat the character.
- character is the character you want to repeat. It can be enclosed in single quotes (‘ ‘) or double quotes (” “).
For example, to repeat the character ‘x’ 10 times:
printf "%*s" 10 x
This command will output “xxxxxxxxxx” (without quotes)
You can also use the yes
command to repeat a character or a string multiple times. For example, to repeat the character “x” 10 times:
yes x | head -n 10
This command will output the same result as the above.
You can also repeat a string multiple times, for example, to repeat the string “Hello” 5 times:
yes "Hello" | head -n 5
This command will output:
Hello
Hello
Hello
Hello
Hello
In addition to that you can use tr
command to repeat a character or a string. For example, to repeat the character “x” 10 times:
echo | tr '\n' x | head -c 10
This command will output the same result as the above two commands.
In all of the above examples, the head
command is used to limit the output to the desired number of repetitions.
It is important to note that the above commands are used to print the repeated characters on the screen. If you want to save the output to a variable or file, you can redirect the output. For example:
output=$(yes x | head -n 10)
This will save the repeated characters “xxxxxxxxxx” to the variable “output”.
yes x | head -n 10 > file.txt
This will save the repeated characters “xxxxxxxxxx” to the file “file.txt”.