Home > Mobile >  Use sed to Replace Multiple Lines
Use sed to Replace Multiple Lines

Time:02-08

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.

CodePudding user response:

awk suited this job better:

awk '/^second$/ {p=1} !p; /^fourth$/ {p=0; print "found"}' file

first
found
fifth
sixth
seventh
eighth

If you really want to use sed then use:

sed '/second/,/fourth/{/second/i\
found
d
}' file

CodePudding user response:

Using sed

$ sed '/second/,/third/{d};x;x;s/fourth/found/' input_file
first
found
fifth
sixth
seventh
eighth

CodePudding user response:

This might work for you (GNU sed):

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

or for those line numbers:

sed '2,4cfound' file

CodePudding user response:

With GNU sed:

sed -z 's/second.*fourth/found/'

Output:

first
found
fifth
sixth
seventh
eighth

-z: separate lines by NUL characters

  •  Tags:  
  • Related