Bash Find and Replace (Substitute) String in a File

In Bash, you can use the sed command to find and replace (substitute) strings within a file. This is a powerful text manipulation tool that allows you to make changes to a file’s content. Below, we’ll go over various examples of using sed for find and replace operations.

General Syntax

The basic syntax for using sed to find and replace is as follows:

1
sed -i 's/word1/word2/g' input_file
  • -i: This option tells sed to edit the file in-place, meaning the changes will be made directly to the file, and the original file will be overwritten.
  • 's/word1/word2/g': This is the substitution command. It tells sed to find all occurrences of word1 and replace them with word2. The g at the end stands for “global,” which means replace all occurrences on each line. You can use a different delimiter instead of / to make the command more readable, such as + or _.

If you want to perform a case-insensitive search and replace, you can add the I flag to the sed command:

1
sed -i 's/word1/word2/gI' input_file

Note for MacOS Users

On macOS, the default sed implementation does not support case-insensitive matching. You can install GNU sed using Homebrew as follows:

1
brew install gnu-sed

Then, you can use gsed instead of sed to perform case-insensitive replacements:

1
gsed -i 's/word1/word2/gI' input_file

Delimiter Character

If the delimiter character / is part of word1 or word2, it can lead to errors. In such cases, you can change the delimiter character to something else, like + or _. For example:

1
sed -i 's+http://+https://www.example.biz+g' input.txt

Examples Without sed

If you want to perform find and replace without using sed, you can use Bash parameter expansion:

Replace the First Occurrence

To replace only the first occurrence of a pattern with a given string, use ${parameter/pattern/string}:

1
2
3
4
5
#!/bin/bash
firstString="I love Suzi and Marry"
secondString="Sara"
echo "${firstString/Suzi/$secondString}"    
# prints 'I love Sara and Marry'

Replace All Occurrences

To replace all occurrences of a pattern with a given string, use ${parameter//pattern/string}:

1
2
3
message='The secret code is 12345'
echo "${message//[0-9]/X}"           
# prints 'The secret code is XXXXX'

These are some common ways to find and replace strings in Bash, depending on your specific needs and preferences.

0%