Bash: How to Replace Multiple Characters in String


You can use the following syntax to replace multiple characters in a string using Bash:

replace_these="s/Mavs/Bengals/;"
replace_these+="s/basketball/football/;"

echo "The Mavs are a basketball team" | sed ${replace_these}

This particular example will make the following replacements in the string:

  • Mavs will be replaced with Bengals.
  • basketball will be replaced with football.

Note: This syntax is case-sensitive.

The following example shows how to use this syntax in practice.

Example: How to Replace Multiple Characters in String in Bash

Suppose that we have the following string:

  • The Mavs are a basketball team

Suppose that we would like to replace multiple words in this string to convert it into the new string:

  • The Bengals are a football team

We can use the following syntax to do so:

replace_these="s/Mavs/Bengals/;"
replace_these+="s/basketball/football/;"

echo "The Mavs are a basketball team" | sed ${replace_these}

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

Replace multiple characters in string using Bash

Notice that the following replacements were made:

  • Mavs was replaced with Bengals.
  • basketball was replaced with football.

Note that in this example we specified two strings to replace but you can use similar syntax to replace as many strings as you would like.

Note: We used sed, a stream editor, with the s/ operator to specify that we would like to substitute one specific pattern with another pattern.

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 Special Characters in String
Bash: How to Replace Specific Line in File

Leave a Reply