7

I'm learning sed's different commands and did some experiments. The command I'm trying is:

root:[~]# seq 7 | sed -n '1~2H; 2~2{G;p}'
2

1
4

1
3
6

1
3
5
root:[~]#

I analyzed the command and to me the last newline character after the number 5 should not exist. Below is my analysis.

enter image description here

Based on my analysis, the output should be the cells with the red color background. As you can see, there is no last newline character. Where am I wrong? Thanks in advance.

9
  • 1
    I don't see a newline as last character. Did you paste the wrong screenshot?
    – eblock
    Commented Aug 29, 2019 at 7:37
  • 1
    If there is no newline, the last line should look like "5root:[~]#" Commented Aug 29, 2019 at 7:39
  • 1
    You can verify by increasing your seq to 8. You'll see that there's no newline after 5.
    – eblock
    Commented Aug 29, 2019 at 7:40
  • 3
    Your image of text isn't very helpful. It can't be copied into an editor, and it doesn't index very well, meaning that other users with the same problem are less likely to find the answer here. Please edit your post to incorporate the relevant text directly (preferably using copy+paste to avoid transcription errors). Commented Aug 29, 2019 at 8:37
  • 2
    Something is not a line of text in UNIX unless it ends with a newline. Unlike Windows, where newlines separate lines, on UNIX, newlines terminate lines, so data without a newline is not part of a well-formed line in a text file on UNIX -- which explains the "why" behind the specification you found. Commented Aug 29, 2019 at 17:50

2 Answers 2

10

p adds the newline character:

% printf 1 | sed 'p;s/1/2/'
1
2%

As can be seen, the 2 is printed without a trailing newline, but the 1 before it, from p, is.

1
  • 5
    Note that the implicit print at the end of the cycle in a non-GNU sed may also add a newline, even if there was no newline in the input (a non-terminated line is not actually valid input to standard sed).
    – Kusalananda
    Commented Aug 29, 2019 at 7:45
6

I think I found the answer. From the POSIX sed's documentation at https://pubs.opengroup.org/onlinepubs/9699919799/utilities/sed.html, it states:

Whenever the pattern space is written to standard output or a named file, sed shall immediately follow it with a newline.

That means the p command will always print pattern space as well as a newline. That also explains why there are newlines after 2\n\n1, 4\n\n1\n3 and 6\n\n1\n3\n5.

Please correct me if you think there is anything wrong with this. Thank you.

1
  • 1
    Exactly. That's it.
    – Philippos
    Commented Aug 29, 2019 at 16:24

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .