Index: usr.bin/sed/defs.h =================================================================== --- usr.bin/sed/defs.h (revision 243746) +++ usr.bin/sed/defs.h (working copy) @@ -143,6 +143,7 @@ char *space; /* Current space pointer. */ size_t len; /* Current length. */ int deleted; /* If deleted. */ + int append_newline; /* If originally terminated by \n. */ char *back; /* Backing memory. */ size_t blen; /* Backing memory length. */ } SPACE; Index: usr.bin/sed/main.c =================================================================== --- usr.bin/sed/main.c (revision 243746) +++ usr.bin/sed/main.c (working copy) @@ -431,8 +431,12 @@ p = fgetln(infile, &len); if (ferror(infile)) errx(1, "%s: %s", fname, strerror(errno ? errno : EIO)); - if (len != 0 && p[len - 1] == '\n') + if (len != 0 && p[len - 1] == '\n') { + sp->append_newline = 1; len--; + } else { + sp->append_newline = 0; + } cspace(sp, p, len, spflag); linenum++; Index: usr.bin/sed/process.c =================================================================== --- usr.bin/sed/process.c (revision 243746) +++ usr.bin/sed/process.c (working copy) @@ -63,6 +63,7 @@ #define pd PS.deleted #define ps PS.space #define psl PS.len +#define panl PS.append_newline #define hs HS.space #define hsl HS.len @@ -85,7 +86,10 @@ size_t maxnsub; regmatch_t *match; -#define OUT() do {fwrite(ps, 1, psl, outfile); fputc('\n', outfile);} while (0) +#define OUT() do { \ + fwrite(ps, 1, psl, outfile); \ + if (panl) fputc('\n', outfile); \ +} while (0) void process(void) @@ -94,6 +98,7 @@ SPACE tspace; size_t oldpsl = 0; char *p; + int oldpanl; p = NULL; @@ -190,11 +195,15 @@ break; if ((p = memchr(ps, '\n', psl)) != NULL) { oldpsl = psl; + oldpanl = panl; psl = p - ps; + panl = 0; } OUT(); - if (p != NULL) + if (p != NULL) { psl = oldpsl; + panl = oldpanl; + } break; case 'q': if (!nflag && !pd) @@ -244,6 +253,7 @@ cspace(&HS, "", 0, REPLACE); tspace = PS; PS = HS; + panl = tspace.append_newline; HS = tspace; break; case 'y': @@ -444,6 +454,7 @@ */ tspace = PS; PS = SS; + panl = tspace.append_newline; SS = tspace; SS.space = SS.back; @@ -513,6 +524,7 @@ /* Swap the translation space and the pattern space. */ tmp = PS; PS = YS; + panl = tmp.append_newline; YS = tmp; YS.space = YS.back; }