Bash: How to Replace Patterns Using Regex


Often you may want to use Bash to replace patterns in a string using Regex.

You can use the following methods to do so:

Method 1: Replace One Pattern Using Regex

echo $my_string | sed -e 's/[0-9]/X/g'

This particular example will replace all numeric characters with the letter X in the variable named $my_string.

Method 2: Replace Multiple Patterns Using Regex

echo $my_string | sed -e 's/[0-9]/X/g' -e 's/HH/L/g'

This particular example will replace all numeric characters with the letter X in and it will replace each pattern of HH with the letter L in the variable named $my_string.

Here is what the various sed commands do:

  • -e: Specifies that the next command should be interpreted as sed command
  • s: Specifies the pattern to “substitute”
  • g: Specifies that the pattern should be replaced “globally”, i.e. all occurrences should be replaced

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

Example 1: Replace One Pattern Using Regex in Bash

Suppose that we create a variable named $my_string in Bash that contains the following characters:

  • AHHB4009R

Suppose that we would like to replace all numbers in this string with the letter X.

We can use the following syntax to do so:

my_string="AHHB4009HR"
echo $my_string | sed -e 's/[0-9]/X/g'

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

Bash regex replace

Notice that all numbers in the string have been replaced with the letter X.

Example 2: Replace Multiple Patterns Using Regex in Bash

Once again, suppose that we create a variable named $my_string in Bash that contains the following characters:

  • AHHB4009R

Suppose that we would like to replace all numbers in this string with the letter X and replace all patterns of HH with L.

We can use the following syntax to do so:

my_string="AHHB4009HR"
echo $my_string | sed -e 's/[0-9]/X/g' -e 's/HH/L/g'

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

Bash Regex replace multiple patterns

Notice that all numbers in the string have been replaced with the letter X and all patterns of HH have been replaced with L.

Note that in this example we replaced two specific patterns but you can use similar syntax to replace as many patterns as you would like in a string.

Related Tutorials

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

Bash: How to Replace Text in String
Bash: How to Replace Specific Line in File
Bash: How to Replace Multiple Characters in String

Leave a Reply