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:
|
|
-i: This option tellssedto 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 tellssedto find all occurrences ofword1and replace them withword2. Thegat 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_.
Case-Insensitive Search
If you want to perform a case-insensitive search and replace, you can add the I flag to the sed command:
|
|
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:
|
|
Then, you can use gsed instead of sed to perform case-insensitive replacements:
|
|
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:
|
|
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}:
|
|
Replace All Occurrences
To replace all occurrences of a pattern with a given string, use ${parameter//pattern/string}:
|
|
These are some common ways to find and replace strings in Bash, depending on your specific needs and preferences.