Can someone please explain why this is happening?
This is expected:
$ echo -e "foo\nbar" | sed -n 'h; x; p'
foo
bar
I put every line in the hold space, then swap hold space and pattern space, then print the pattern space, so every line is printed. Now, why is the following different?
$ echo -e "foo\nbar" | sed -n 'h; d; x; p'
I thought that wouldn't be, because I delete the pattern space before swapping, so the stored line should be put back to the pattern space anyway. It's the hold space that should be empty after x;
, right? I delete the pattern space, then swap. Where does the line I've saved go?
When you use d
, the pattern space is cleared, the next line is read, and processing starts over from the beginning of the script. Thus, you never actually reach the x
and p
steps, instead just copying to the hold space and deleting.
I guess it's related to the following line in man sed
:
d Delete pattern space. Start next cycle.
The following works as expected:
$ echo -e "foo\nbar" | sed -n 'h; s/.*//; g; p'
foo
bar
Sorry for bothering you guys.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With