How to Use sed to Replace nth Occurrence of Pattern


Often you may want to use sed to replace the nth occurrence of a specific pattern in a file.

You can use the following methods to do so:

Method 1: Replace nth Occurrence in Entire File

sed -z 's/West/East/2' team_names.txt

This particular example replaces the string “West” with the string “East” only for the second occurrence of “West” in the entire file named team_names.txt.

Method 2: Replace nth Occurrence in Each Line of File

sed 's/West/East/2' team_names.txt

This particular example replaces the string “West” with the string “East” for the second occurrence of “West” in each line of the file named team_names.txt.

Note that in both examples we use the following syntax to substitute one pattern for another pattern:

  • s/old_pattern/new_pattern/occurrence

The following examples show how to use each method in practice with the following file named team_names.txt:

Example 1: Replace nth Occurrence in Entire File

We can use the following syntax to replace the second occurrence of the pattern “West” in the entire file named team_names.txt:

sed -z 's/West/East/2' team_names.txt

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

sed replace nth occurrence in entire file

Notice that only the second occurrence of “West” has been replaced in the entire file.

All other occurrences of “West” remain untouched.

Note that we used the sed -z flag to interpret the entire text file as one string instead of individual lines separated by newline characters.

Example 2: Replace nth Occurrence in Each Line of File

We can use the following syntax to replace the second occurrence of the pattern “West” in each line of the file named team_names.txt:

sed 's/West/East/2' team_names.txt

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

sed replace nth occurrence of pattern in each line of file

Notice that the second occurrence of “West” has been replaced in each line of the file.

For lines that only have one occurrence of “West”, no replacement is made.

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 Replace Last Occurrence of Character in String
How to Use sed to Replace All Occurrences of Pattern
How to Use sed to Replace All Text After Match

Leave a Reply