Issue
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?
Solution
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
)
Answered By - Beano Answer Checked By - Marilyn (WPSolving Volunteer)