In this short article, we will see how to replace a string with another in bash script. We will cover multiple examples and situations.

Suppose we have 3 variables:

text="Hello World!"
repl="Bash"
str_find="World"

where:

  • text - the main string from which we will replace
  • repl - the new string / replacement
  • str_find - the search pattern which will be replaced

The image below shows most examples and results of string replacement in bash:

Replace substring with new in string

We use the following syntax to replace string in Bash:

${text/pattern/replacement}

Example of replacing string with /:

text="Hello World! World!"
repl="Bash"
str_find="World"
echo "${text/$str_find/"$repl"}"    

In this example we get:

Hello Bash! World!

The code above will replace only the first match. To replace all occurrences, check the next solution.

bash replace all occurrences string

echo "${text//$str_find/"$repl"}"    

To replace all occurrences of substring in text we need to use Bash operator - //.

replace string by sed

result=$(echo "$text" | sed "s/$str_find/$repl/")

sed - replace all occurrences

by adding g at the end of the sed command we can replace all occurrences of given pattern in a string

result=$(echo "$text" | sed "s/$str_find/$repl/g")

replace string by empty string

echo "${text//$str_find/""}"

or

repl=""
echo "${text/$str_find/"$repl"}"    

regex: search and replace

We can use regex to replace all letters or numbers from string in bash:

text="Hello World! 735!"
echo ${text//[a-zA-Z]/W}
echo ${text//[0-9]/N}

The new string after the replacements looks like

WWWWW WWWWW! 735!
Hello World! NNN!

regex + sed: search and replace

We can use regex to search for a pattern and replace all matches in bash script:

text="Hello World! 735!"
echo "$text" | sed -e 's/[a-zA-Z]/W/g' -e 's/[0-9]/N/g'

the result is replace all letters with W and digits by D:

WWWWW WWWWW! NNN!

replace all newlines to space

text="line 1
line 2
end"
echo "${text//$'\n'/ ;}"

result:

line 1 ;line 2; end