Bash: How to Repeat a Character N Times


Often you may want to repeat a character a certain number of times in Bash.

You can use the following methods to do so:

Method 1: Repeat Character N Times

printf 'A%.0s' {1..10}

This particular example repeats the character “A” a total of 10 times.

Method 2: Repeat Character the Same Number of Times as String Length

echo $my_string;printf -- '=%.0s' $(seq 1 ${#my_string})

This particular example repeats an equal sign ( = ) the same number of times as the length of the string variable named $my_string.

The following examples show how to use each of these methods in practice.

Example 1: Repeat Character N Times in Bash

Suppose that we would like to repeat the character “A” a total of 10 times in Bash.

We can use the following syntax to do so:

printf 'A%.0s' {1..10}

The following screenshot shows how to use this syntax in practice:

Bash repeat character N times

The output displays the character “A” repeated a total of 10 times.

Feel free to replace A with any other character that you would like.

Also feel free to replace the 10 with any other number to instead repeat the character a different number of times.

Example 2: Repeat Character the Same Number of Times as String Length in Bash

Suppose that we have a string variable stored in Bash named $my_string and we would like to display the string with equal signs ( = ) shown below each character in the string.

We can use the following syntax to do so:

my_string="Hello there everyone"

echo $my_string;printf -- '=%.0s' $(seq 1 ${#my_string})

The following screenshot shows how to use this syntax in practice:

Bash repeat character same number of times as length of string

The output displays the string with an equal sign ( = ) shown below each character in the string.

Note: Feel free to replace the equal sign ( = ) sign with any other character that you would like to repeat below your string.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Get First N Characters from String
Bash: How to Get Last N Characters from String
Bash: How to Count Number of Characters in String

Leave a Reply