command D in sed - output seems different from what the manual says

Viewed 118

Found the following in the sed manual about the command D,

D - If pattern space contains no newline, start a normal new cycle as if the d command was issued. Otherwise, delete text in the pattern space up to the first newline, and restart cycle with the resultant pattern space, without reading a new line of input

But the example I try do not seem to match what is described above.

$cat test
LINE 101
LINE 201
LINE 301
LINE 401

$ sed -nr '1{p;N;p;D;}' test
LINE 101
LINE 101
LINE 201

The way I understood based on the sed manual description is as follows,

  1. print the pattern space (LINE 101)
  2. Append LINE 201 to the pattern space print the pattern space (LINE 101 \n LINE 201)
  3. Delete up to the first new line in the pattern space. The pattern space will now have LINE 201
  4. Now sed manual says "and restart cycle with the resultant pattern space, without reading a new line of input" - That would mean go back to the beginning of the command? If that's how it is, then we should have an output of - LINE 201, LINE 201 \n LINE 301 and on like that in a loop till the end.

But that's not the output I see.

1 Answers

I think the answer is contained in @potong's comment already.

Concerning why the OP was surprised by sed's behavior, I can only speculate that it is due to the wording of his point 2:

Append LINE 201 to the pattern space print the pattern space (LINE 101 \n LINE 201)

which leaves room for the following wrong interpretation:

N picks the next line of input and appends it to the current pattern space (with a newline in between); then, when the end of script is reached, the same next line of input is read.

This would mean that LINE 201 is processed twice. On the contrary, it is processed only once, as N reads a new line of input and appends it to the content of the pattern space.

Related