How to Use sed to Replace Multiple Strings (With Examples)


Often you may want to use sed to replace multiple strings at once.

There are two common ways to do so:

Method 1: Replace Multiple Strings with Multiple New Strings

sed 's/Guard/Gd/g; s/Center/Cn/g' player_info.txt

This particular example makes the following replacements in the file named player_info.txt:

  • All occurrences of Guard are replaced with Gd
  • All occurrences of Center are replaced with Cn

Method 2: Replace Multiple Strings with One New String

sed 's/\(Guard\|Forward\)/Athlete/g' player_info.txt

This particular example makes the following replacements in the file named player_info.txt:

  • All occurrences of Guard and Forward are replaced with Athlete

Here is what the various sed commands do:

  • s: Used to “substitute” one pattern for another
  • g: Used to make substitutions “globally”, i.e. for all occurrences

The following examples show how to use each method in practice with the following file named player_info.txt that contains information about the positions of basketball players on various teams:

Example 1: Use sed to Replace Multiple Strings with Multiple New Strings

Suppose that we would like to make the following replacements in the file named player_info.txt:

  • Replace all occurrences of Guard with Gd
  • Replace all occurrences of Center with Cn

We can use the following syntax to do so:

sed 's/Guard/Gd/g; s/Center/Cn/g' player_info.txt

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

sed replace multiple strings

Both strings that we specified were replaced with new strings in each line of the file.

Example 2: Use sed to Replace Multiple Strings with One New String

Suppose that we would like to make the following replacements in the file named player_info.txt:

  • Replace all occurrences of Guard and Forward with Athlete

We can use the following syntax to do so:

sed 's/\(Guard\|Forward\)/Athlete/g' player_info.txt

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

sed replace multiple strings with one new string

Notice that all occurrences of Guard and Forward have been replaced with Athlete in each line.

Related Tutorials

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

How to Use Case-Insensitive Search and Replace in sed
How to Use sed to Replace newline with space
How to Use sed to Replace All Occurrences of Pattern
How to Use sed to Replace All Text Before Match

Leave a Reply