Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I delete a matching line, the line above and the one below it, using sed?

Tags:

regex

sed

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?

like image 753
Ben Lever Avatar asked May 18 '09 06:05

Ben Lever


People also ask

How do I delete a specific line?

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.

How do I delete a specific line in Unix?

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.

How do I remove a specific pattern from a Unix file?

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.

How do you delete a line in Linux?

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”.


1 Answers

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)

like image 72
Beano Avatar answered Sep 22 '22 09:09

Beano