Skip to content
Advertisement

Match two lines, replace with three lines

I need to use sed to replace every matching two-line pattern with a three line pattern. Here’s my input file (tempfile.txt).

JavaScript

Basically, if a client-hostname "HOSTNAME"; is missing, then it should be replaced with a tab and then a newline.

My attempt: sed 'N; /hardware.*}/d; P; D' tempfile.txt

The result is:

JavaScript

This is my desired output.

JavaScript

So as you can see, there are consistently three lines between the curlies. That’s what I’m aiming for.

Advertisement

Answer

This does the trick (piping to cat -A to show non-printable characters):

JavaScript

Instead of deleting matches, this captures the two lines supposed to surround the empty line and replaces with the newline and tab between. I’ve also added a few anchors for safer matching.

There is a bit of trickery involved because the pattern space contains two newlines after a substitution, but P;D prints only the first line and the starts a new cycle, which leads to unwanted newlines also after lines containing client-hostname.

Explained in more detail:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement