How to Use sed to Replace Only the First Occurrence in a File


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

You can use the following basic syntax to do so:

sed '0,/Celtics/s//Nuggets/' team_list.txt

This particular example replaces only the first occurrence of “Celtics” with “Nuggets” in the file named team_list.txt.

This syntax does the following: Start at line 0, continue until you encounter a line with the pattern “Celtics” and then substitute that line with the pattern “Nuggets” instead.

We then leave the rest of the file untouched, which allows us to only replace the first occurrence of “Celtics” and no other occurrences.

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

Example: Use sed to Replace Only First Occurrence in a File

Suppose that we have a file named team_list.txt that contains the names of various basketball teams:

Notice that the team name “Celtics” occurs multiple times in the file.

Suppose that we would like to replace only the first occurrence of “Celtics” with the team name “Nuggets” instead.

We can use the following syntax to do so:

sed '0,/Celtics/s//Nuggets/' team_list.txt

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

sed only replace first occurrence in file

Notice that only the first occurrence of “Celtics” is replaced in the file (on line number 1) while all other occurrences of “Celtics” on all other lines are left untouched.

Note: If you would like to modify the file in-place, then you can use the -i flag as follows:

sed '0,/Celtics/s//Nuggets/' team_list.txt

This will replace the first occurrence of “Celtics” with “Nuggets” in the file in-place.

Related Tutorials

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

How to Use sed to Replace All Text After Match
How to Use sed to Replace All Occurrences of Pattern
How to Use sed to Replace Last Occurrence of Character in String

Leave a Reply