Skip to content

sed - s///g writes the replacement between the bytes of a UTF-8 character at empty matches #644

Open

Description

@sylvestre

In a UTF-8 locale, a regex that can match the empty string ([0-9]*, x*, ...) used with the
g flag (or a number of 2 or more) inserts the replacement inside multibyte characters. A
valid UTF-8 line comes out as invalid UTF-8, with exit status 0. GNU sed only considers empty
matches at character boundaries.

Reproduction

The input is é (bytes c3 a9).

Rust (incorrect)

$ printf '\303\251\n' | LC_ALL=C.UTF-8 ./target/release/sed 's/[0-9]*/N/g' | od -An -tx1
 4e c3 4e a9 4e 0a
# Exit code: 0

GNU (correct)

$ printf '\303\251\n' | LC_ALL=C.UTF-8 /usr/bin/sed 's/[0-9]*/N/g' | od -An -tx1
 4e c3 a9 4e 0a
# Exit code: 0

Likewise s/[0-9]*/N/2 replaces inside the character, and s/[0-9]*/N/3 finds a third match
that GNU does not have.

Root cause

substitute in src/sed/processor.rs iterates over regex.captures_iter(...)
(src/sed/processor.rs:349-356) on the byte-oriented engine and counts every match:

for caps_result in regex.captures_iter(pattern)? {
    ...
    count += 1;

    let m = caps.get(0)?.unwrap();

The byte engine reports an empty match at every byte offset, including offsets inside a
multibyte character.

Test

#[rstest]
#[case::global("s/[0-9]*/N/g", "N\u{e9}N\n")]
#[case::second("s/[0-9]*/N/2", "\u{e9}N\n")]
#[case::third("s/[0-9]*/N/3", "\u{e9}\n")]
fn test_empty_match_respects_utf8_boundaries(#[case] script: &str, #[case] expected: &str) {
    new_ucmd!()
        .env("LC_ALL", "C.UTF-8")
        .arg(script)
        .pipe_in("\u{e9}\n")
        .succeeds()
        .stdout_is(expected);
}

Reported by Anthropic's OSS Scanner (ANT-2026-SV2WZM84).

Activity

  1. added
    bug
    good first issue
    oss-scanner
    gnu-compat
    on Nov 9, 2026
  2. added a commit that references this issue on Nov 26, 2026
    87942e0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    buggnu-compatgood first issueoss-scanner

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions