How to Use sed to Replace All Occurrences of Pattern


You can use the s operator in sed to replace one particular pattern in a string with another pattern:

sed 's/Guard/point_guard/' player_info.txt

This particular example replaces the first occurrence of “Guard” with “point_guard” in each line of the file named player_info.txt.

In order to replace all occurrences of “Guard” in each line of the file, you must use the g operator to specify that the pattern should be replaced “globally” i.e. all occurrences should be replaced:

sed 's/Guard/point_guard/g' player_info.txt

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

Example: How to Use sed to Replace All Occurrences of Pattern

Suppose that we have a file named named player_info.txt that contains the positions of basketball players on various teams.

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

Suppose that we would like to replace each occurrence of “Guard” with “point_guard” in each line.

Suppose that we attempt to use the following syntax to do so:

sed 's/Guard/point_guard/' player_info.txt

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

Notice that only the first occurrence of “Guard” is replaced with “point_guard” in each line.

In order to replace all occurrences of “Guard” in each line we must use the g operator to specify that all occurrences should be replaced:

sed 's/Guard/point_guard/g' player_info.txt

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

sed replace all occurrences

Notice that all occurrences of “Guard” are replaced with “point_guard” in each line.

Related Tutorials

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

How to Use sed to Replace newline with space
How to Use sed to Replace newline with comma
Bash: How to Replace Special Characters in String
Bash: How to Replace Multiple Characters in String

Leave a Reply