diff --git a/src/sed/processor.rs b/src/sed/processor.rs index 4dde35f3..845a286c 100644 --- a/src/sed/processor.rs +++ b/src/sed/processor.rs @@ -85,6 +85,8 @@ fn applies( context: &mut ProcessingContext, ) -> UResult { let linenum = context.line_number; + // Set below when this line ends a range; read by `c`. + context.last_address = false; let result = if command.addr1.is_none() && command.addr2.is_none() { // No address @@ -99,6 +101,10 @@ fn applies( command.start_line = None; Ok(false) } else { + if linenum - start == *n { + command.start_line = None; + context.last_address = true; + } Ok(true) } } @@ -108,6 +114,10 @@ fn applies( command.start_line = None; Ok(false) } else { + if linenum == *n { + command.start_line = None; + context.last_address = true; + } Ok(true) } } @@ -742,10 +752,10 @@ fn process_file( break; } 'c' => { - // At range end replace pattern space with text and - // start the next cycle. + // Print the text at the end of a range, or for every line + // when the range is negated, then start the next cycle. pattern.clear(); - if command.addr2.is_none() || context.last_address || reader.last_line()? { + if command.addr2.is_none() || command.non_select || context.last_address { let text = extract_variant!(command, Text); output.write_bytes(text.as_ref())?; } diff --git a/tests/by-util/test_sed.rs b/tests/by-util/test_sed.rs index 7c408df2..f53169d1 100644 --- a/tests/by-util/test_sed.rs +++ b/tests/by-util/test_sed.rs @@ -2221,6 +2221,44 @@ fn test_change_command_prevents_automatic_printing() { .stdout_is("line1\nreplaced\nline3"); } +#[test] +fn test_change_command_prints_text_at_range_end() { + for (script, expected) in [ + ("2,4c\\X", "1\nX\n5\n6\n"), + ("2,+2c\\X", "1\nX\n5\n6\n"), + ("2,~4c\\X", "1\nX\n5\n6\n"), + ("4,~4c\\X", "1\n2\n3\n"), + ("2,4!c\\X", "X\n2\n3\n4\nX\nX\n"), + ("5,8c\\X", "1\n2\n3\n4\n"), + ("/2/,/3/c\\X\n6,8c\\Y", "1\nX\n4\n5\n"), + ] { + new_ucmd!() + .arg(script) + .pipe_in("1\n2\n3\n4\n5\n6\n") + .succeeds() + .stdout_is(expected); + } +} + +#[test] +fn test_range_with_line_end_restarts_on_next_line() { + new_ucmd!() + .arg("/a/,3d") + .pipe_in("a\na\na\na\nb\n") + .succeeds() + .stdout_is("b\n"); + new_ucmd!() + .arg("/a/,+1d") + .pipe_in("a\na\na\na\nb\n") + .succeeds() + .stdout_is("b\n"); + new_ucmd!() + .arg("/a/,+1c\\X") + .pipe_in("a\na\na\na\nb\n") + .succeeds() + .stdout_is("X\nX\nb\n"); +} + #[test] fn test_uppercase_delete_prevents_automatic_printing() { // Test 'D' command - delete up to newline and restart