Bash: How to Replace Specific Text in Multiple Files


You can use the following syntax in Bash to replace specific text in multiple files:

sed -i 's/Mavs/Mavericks/g' *

This particular example will replace the text “Mavs” with “Mavericks” in every file in the current directory.

Here is what the various sed commands do:

  • -i: Specifies that files should be modified in-place
  • s: Used to “substitute” one pattern for another pattern
  • g: Specifies that substitutions should be made “globally”, i.e. for all occurrences of the pattern
  • *: Specifies that the substitution should be made in all files in the current directory

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

Example: How to Replace Specific Text in Multiple Files in Bash

Suppose that our current directory contains the following three text files:

  • teams1.txt
  • teams2.txt
  • teams3.txt

We can use the cat command to view the contents of each of these files:

Each of the files contain the names of various basketball teams.

Suppose that we would like to replace the team name “Mavs” with “Mavericks” in each file.

We can use the following syntax to do so:

sed -i 's/Mavs/Mavericks/g' *

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

Bash replace text in multiple files

Notice that when we use the cat command to view the updated contents of each file we can see that the pattern “Mavs” has been replaced with “Mavericks” in each file that contained the pattern.

Feel free to replace “Mavs” with any other pattern that you would like to search for in your own files.

Related Tutorials

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

Bash: How to Replace Patterns Using Regex
Bash: How to Replace All Occurrences of String in File
Bash: How to Replace Special Characters in String

Leave a Reply