vermtech
vermtech

Reputation: 31

'N' and 'D' not working as expected with sed

sed 'N; D' testfile

testfile contains:

this is the first line
this is the second line
this is the third line
this is the fourth line

I am using RHEL 6 and the output comes as:

this is the fourth line

As per my understanding, N just pulls in the next line into the pattern space and D deletes just the first line of the pattern space. Therefore, the output should have been:

this is the second line
this is the fourth line

Can someone please explain why the output is coming as mentioned above?

Upvotes: 3

Views: 335

Answers (2)

Andreas Louv
Andreas Louv

Reputation: 47119

As already shown using D will move to the beginning of program. You can however use the following to print even lines:

sed -n 'n;p'

and to print odds:

sed 'n;d'

In GNU sed you can also use:

sed '0~2!d' # Odd
sed '1~2!d' # Even

An alternative can be something like:

N;s/^[^\n]*\n//

which will read the next line into the pattern space and then substitute the first away.

One might ask why this is the behavior. One reason is to make things like this possible, working with multiply lines in the pattern space:

$!N;/\npattern$/d;P;D

The above will delete lines matching pattern as well as the line before.

Upvotes: 1

melpomene
melpomene

Reputation: 85837

According to the documentation:

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.

(Emphasis mine.)

It sounds like this would restart your sed program from the beginning, reading and deleting lines until it runs out of input, at which point only the last line is left in the buffer.

Upvotes: 4

Related Questions