diff --git a/src/uu/pr/src/pr.rs b/src/uu/pr/src/pr.rs index ca234defd58..c98d8b2e908 100644 --- a/src/uu/pr/src/pr.rs +++ b/src/uu/pr/src/pr.rs @@ -92,6 +92,8 @@ struct FileLine { page_number: usize, line_number: usize, line_content: Vec, + /// The last line of the input, which has no newline. + unterminated: bool, } impl FileLine { @@ -130,6 +132,7 @@ impl FileLine { page_number, line_number, line_content, + unterminated: false, }) } } @@ -1289,7 +1292,8 @@ fn get_pages( // Consider all trailing bytes as the last line. if prev < buf.len() { - let file_line = FileLine::from_buf(file_id, page_num, line_num, &buf[prev..], options)?; + let mut file_line = FileLine::from_buf(file_id, page_num, line_num, &buf[prev..], options)?; + file_line.unterminated = true; page.push(file_line); } @@ -1635,7 +1639,18 @@ fn write_columns( if cells_written == 0 && not_found_break && no_trailer { break; } - writer.write_all(line_separator)?; + // Like GNU pr, -d adds its blank line only after a line that ended + // with a newline, so an input whose last line lacks one ends there. + // With a header and trailer the page is padded to its length anyway. + let single_unterminated = !options.display_header_and_trailer + && !merge + && columns == 1 + && matches!(row.first(), Some(Some(line)) if line.unterminated); + if single_unterminated { + writer.write_all(b"\n")?; + } else { + writer.write_all(line_separator)?; + } } Ok(()) diff --git a/tests/by-util/test_pr.rs b/tests/by-util/test_pr.rs index d56a50a451e..dc1ac34438a 100644 --- a/tests/by-util/test_pr.rs +++ b/tests/by-util/test_pr.rs @@ -1711,3 +1711,14 @@ fn test_page_width_narrower_than_leading_tab() { .succeeds() .stdout_only(" 1\t\n 2\t\n"); } + +#[test] +fn test_double_space_last_line_without_newline() { + for (input, expected) in [("a", "a\n"), ("a\nb", "a\n\nb\n"), ("a\nb\n", "a\n\nb\n\n")] { + new_ucmd!() + .args(&["-t", "-d"]) + .pipe_in(input) + .succeeds() + .stdout_only(expected); + } +}