sed: Replace string based on line number (certain line)

Here our requirement is that we have a file where we have to perform a string replacement but based on line number.

Below is our sample data /tmp/file
1 This is line one
2 This is line two
3 This is line three
4 This is line four
5 This is line one
6 This is line two
7 This is line three
8 This is line four

Example 1
Replace “one” with “your text” at line number 5, note that the replacement must only happen at line number 5 as we also have ‘one’ at line number 1

Solution
# sed ‘5s/one/your text/g’ /tmp/file

1 This is line one
2 This is line two
3 This is line three
4 This is line four
5 This is line your text
6 This is line two
7 This is line three
8 This is line four
To perform in line replacement in the same file
# sed -i ‘5s/one/your text/g’ /tmp/file

Example 2
Replace “four” with “your text” at line number 8, note that the replacement must only happen at line number 5 as we also have ‘four’ at line number 4

Solution
# sed ‘8s/four/your text/g’ /tmp/file

1 This is line one
2 This is line two
3 This is line three
4 This is line four
5 This is line one
6 This is line two
7 This is line three
8 This is line your text
To perform in line replacement in the same file
# sed -i ‘8s/four/your text/g’ /tmp/file

IMPORTANT NOTE :  Do not use this unless you are very sure the command will not impact anything else, it is always recommended to take a backup of such file where you plan to do in place replacement

Leave a Comment