Why doesn't sed's automatic printing deliver the expected results?
- by CodeGnome
What Works
This sed script works as intended:
$ echo -e "2\n1\n4\n3" | sed -n 'h; n; G; p'
1
2
3
4
It takes pair of input lines at a time, and swaps the lines. So far, so good.
What Doesn't Work
What I don't understand is why I can't use sed's automatic printing. Since sed automatically prints the pattern space at the end of each execution cycle (except when it's suppressed), why is this not equivalent?
$ echo -e "2\n1\n4\n3" | sed 'h; n; G'
2
1
2
4
3
4
What I think the code says is:
The input line is copied to the hold space.
The next line is read into the pattern space.
The hold space is appended to the pattern space.
The pattern space (line1 + newline + line2) is printed automatically because we've reached the end of the execution cycle.
Obviously, I'm wrong...but I don't understand why. Can anyone explain why this second example breaks, and why print suppression is needed to yield the correct results?