Replace Substring in String

To replace a substring with new value in a string in Bash Script, we can use sed command. sed stands for stream editor and can be used for find and replace operation.

We can specify to sed command whether to replace the first occurrence or all occurrences of the substring in the string.

In this tutorial, we will learn how to replace first or all occurrences of a specific substring with new value in given string, with examples.

Syntax

The syntax to replace the first occurrence of substring with new value in the given string is

</>
Copy
sed "s/oldstring/newstring/"

The syntax to replace all occurrences of substring with new value in the given string is

</>
Copy
sed "s/oldstring/newstring/g"

The difference between these two expressions is the g at the end of argument in the second expression.

Examples

Replace First Occurrence

In the following script, we take a string in str, and replace the first occurrence of “hello” with “apple”.

Example.sh

</>
Copy
str="hello world, hello earth"
oldstr="hello"
newstr="apple"
result=$(echo $str | sed "s/$oldstr/$newstr/")
echo "Original String :  $str"
echo "Replaced String :  $result"

Output

Original String :  hello world, hello earth
Replaced String :  apple world, hello earth

Only the first occurrence of old substring “hello” is replaced with new value “apple”.

Replace All Occurrences

To replace all occurrences we use the second expression mentioned in the syntax section, with the g at the end of the argument to sed command.

Example.sh

</>
Copy
str="hello world, hello earth"
oldstr="hello"
newstr="apple"
result=$(echo $str | sed "s/$oldstr/$newstr/g")
echo "Original String :  $str"
echo "Replaced String :  $result"

Output

Original String :  hello world, hello earth
Replaced String :  apple world, apple earth

All the occurrences of old substring are replaced with new value.

Conclusion

In this Bash Tutorial, we have learnt how to replace a substring with new value in given string in Bash Script using sed command.