Sunday, September 4, 2022

[SOLVED] Use sed to Replace Multiple Lines

Issue

I'm trying to use sed to replace multiple lines which are found via regex with one substitution. For example, given the following simplified text file

first
second
third
fourth
fifth
sixth
seventh
eighth

How would I go about using regex to find the second to fourth lines and replace the whole range with one instance of the word "found" so that the end result is

first
found
fifth
sixth
seventh
eighth

I'm basically looking to combine the substitution syntax (sed 's/second/found/') with the range syntax (sed '/second/,/fourth/') into something like sed 's/second/,/fourth/found/' that actually works.


Solution

This might work for you (GNU sed):

sed '/second/,/fourth/cfound' file

or for those line numbers:

sed '2,4cfound' file


Answered By - potong
Answer Checked By - Terry (WPSolving Volunteer)