How to Use sed to Apply Changes to Multiple Files


Often you may want to use sed to apply changes to multiple files at once.

You can use the following basic syntax to do so:

find . -type f -name '*teams*' | xargs sed -i 's/Guard/Gd/g'

Here is what this particular example does:

  • First find all files that contain the string “teams” in the current directory
  • Then, replace each occurrence of “Guard” with “Gd” in each file

Here is what the various sed commands do:

  • -i: Modify the files in-place
  • s: Substitute a particular pattern with a new pattern
  • g: Make the substitution “globally”, i.e. for all occurrences of the pattern

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

Example: Use sed to Apply Changes to Multiple Files

Suppose that our current directory has the following four files:

  • teams1.txt
  • teams2.txt
  • coaches.txt
  • managers.txt

Suppose that we would like to apply changes to only the files that contain the string “teams” in the file name.

We can first use the cat command to view the contents of each file that contains “teams” in the file name:

Suppose that we would like to replace each occurrence of “Guard” with “Gd” in each of these files.

We can use the following syntax to do so:

find . -type f -name '*teams*' | xargs sed -i 's/Guard/Gd/g'

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

sed change multiple files

Notice that each occurrence of “Guard” has been replaced with “Gd” in both files that contained the string “teams” in the file name.

Feel free to replace ‘*teams*’ with a different string to instead apply changes to files that contain a different pattern.

Related Tutorials

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

How to Use sed to Replace newline with space
How to Use sed to Extract All Lines Containing a Pattern
How to Use sed to Replace Entire Line that Contains Pattern

Leave a Reply