Bash: How to Replace All Occurrences of String in File


You can use the following syntax in Bash to replace all occurrences of a specific string in a file:

sed -i 's/Atlanta/Dayton/g' c:/users/bobbi/cities.txt

This particular example replaces all occurrences of the string “Atlanta” with the new string “Dayton” in the file named cities.txt.

The -i tells Bash to make the substitution in-place in the file.

The /s tells Bash to make a substitution. 

The first word following /s specifies the string to substitute and the second word specifies the new string to use as the substitution.

The /g stands for “global replacement” and tells Bash to replace all occurrences of the specific string in the file rather than just the first occurrence.

The following example shows how to use this syntax in practice.

Example: How to Replace All Occurrences of String in File in Bash

Suppose that we have a text file located at the following path:

  • c:/users/bobbi/cities.txt

We can use the cat statement to view the contents of this file:

We can see that the text file currently contains the names of various cities.

Suppose that we would like to replace each occurrence of “Atlanta” with the string “Dayton” instead.

We can use the following syntax to do so:

sed -i 's/Atlanta/Dayton/g' c:/users/bobbi/cities.txt

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

Bash replace all occurrences of string in file

Notice that all three occurrences of “Atlanta” have been replaced with “Dayton” in the file.

Note: This syntax is case-sensitive. The string that we search for must match the case that we specify in order for it to be replaced.

If you’d like to perform a case-insensitive replacement, you can use the following syntax instead:

sed -i 's/Atlanta/Dayton/I' c:/users/bobbi/cities.txt

The uppercase I operator at the end specifies that Bash should use a case-insensitive replacement.

Related Tutorials

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

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

Leave a Reply