I have the following sequence occurring multiple times in a file:
yyyy
xxxx
zzzz
I have a regex that matches xxxx
. Whenever there is a match, I want to delete that line, the line before (e.g. yyyy
) and the line after it (e.g. zzzz
). How can I use sed to do this?
Delete lines or connectorsClick the line, connector, or shape that you want to delete, and then press Delete. Tip: If you want to delete multiple lines or connectors, select the first line, press and hold Ctrl while you select the other lines, and then press Delete.
To delete a line, we'll use the sed “d” command. Note that you have to declare which line to delete. Otherwise, sed will delete all the lines.
N command reads the next line in the pattern space. d deletes the entire pattern space which contains the current and the next line. Using the substitution command s, we delete from the newline character till the end, which effective deletes the next line after the line containing the pattern Unix.
To delete a line, follow the steps below: First, bring your cursor to the line you want to delete. Press the “Esc” key to change the mode. Now type, “:d”, and press “Enter” to delete the line or quickly press “dd”.
The trick is to store the last line seen in the "hold space".
sed -n '
/^xxxx/{n
n
x
d
}
x
1d
p
${x
p
}
' <input file>
Starting with the x
- swap the current input line with the hold space (x
), then for the first line don't print anything (1d
), subsequent lines print the line just swapped from the hold space (p
), on the last line swap the hold space again and print what was in it ($x{x p}
. That leaves what to do when we hit the target line (starting /^xxxx/
) - read the next two lines into the pattern space (n n
) and swap the pattern space with the hold space (x
) - this leaves the hold space with next line we want to print and the pattern space with the line before the match, which we don't want, so we ditch it (d
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With