Bash: How to Replace Text in String


There are two common ways to replace specific text in strings in Bash:

Method 1: Replace First Occurrence of Text

my_string=${my_string/basketball/football}

This particular example will replace the first occurrence of the string “basketball” with the string “football” in the variable named $my_string.

Method 2: Replace All Occurrences of Text

my_string=${my_string//basketball/football}

This particular example will replace all occurrences of the string “basketball” with the string “football” in the variable named $my_string.

Note that the only difference between this example and the previous one is that we used double slashes ( // ) after the variable name to indicate that we’d like to replace all occurrences of a specific string.

The following examples show how to use each method in practice.

Example 1: Replace First Occurrence of Text in String in Bash

Suppose that we create a variable in Bash that contains the following string:

  • “I think basketball is a wonderful sport”

Suppose that we would like to replace “basketball” with “football” so that the new string contains the following:

  • “I think football is a wonderful sport”

We can use the following syntax to do so:

$my_string="I think basketball is a wonderful sport"
my_string=${my_string/basketball/football} 

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

Bash replace text in string

Notice that “basketball” has been replaced with “football” in the variable named $my_string.

If you would like to simply remove the text “basketball” from the string then you can replace the text with nothing instead:

$my_string="I think basketball is a wonderful sport"
my_string=${my_string/basketball/} 

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

Bash replace text in string with nothing

Notice that “basketball” has simply been removed from the string.

Note: This method is case-sensitive.

Example 2: Replace All Occurrences of Text in String in Bash

Suppose that we create a variable in Bash that contains the following string:

  • “basketball is great and basketball is fun”

Suppose that we would like to replace each occurrence of “basketball” with “football” so that the new string contains the following:

  • “football is great and football is fun”

We can use the following syntax to do so:

$my_string="basketball is great and basketball is fun"
my_string=${my_string//basketball/football} 

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

Bash replace each occurrence of text in string

Notice that each occurrence of “basketball” has been replaced with “football” in the variable named $my_string.

Related Tutorials

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

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

Leave a Reply