Skip to content

grep - with -z, ^ and $ also match next to a newline inside a record #195

Description

@sylvestre

With -z/--null-data a record ends at NUL and newline is ordinary data. GNU grep anchors
^ and $ only at the start and end of the record, so ^two does not match the record
one\ntwo. uu_grep lets ^ match right after every embedded newline and $ right before
it (BRE/ERE), and under -P it lets $ match before a trailing newline. #25/#45 fixed .
for -z; the anchors were left with Oniguruma's line semantics.

Exposed by the GNU tests z-anchor-newline (-z '^[a-b]*$' etc. on a\nb\0, in a UTF-8
locale, but the C locale behaves the same) and pcre (printf 'x\n\0' | grep -zP 'x$' must
not match).

Reproduction

Rust (incorrect)

$ printf 'one\ntwo\0' | ./target/release/grep -z -c '^two'
1
# Exit code: 0

$ printf 'one\ntwo\0' | ./target/release/grep -z -c 'one$'
1
# Exit code: 0

$ printf 'one\n\0' | ./target/release/grep -zP -c 'one$'
1
# Exit code: 0

GNU (correct)

$ printf 'one\ntwo\0' | LC_ALL=C /usr/bin/grep -z -c '^two'
0
# Exit code: 1

$ printf 'one\ntwo\0' | LC_ALL=C /usr/bin/grep -z -c 'one$'
0
# Exit code: 1

$ printf 'one\n\0' | LC_ALL=C /usr/bin/grep -zP -c 'one$'
0
# Exit code: 1

Root cause

src/matcher.rs:321-326: the only -z adjustment is REGEX_OPTION_MULTILINE, which in
Oniguruma only makes . match a newline. The grep/GNU-regex syntaxes keep ^/$ as line
anchors, and the Perl syntax keeps $ matching before a final newline; nothing switches them
to record (whole-subject) anchors under -z:

if config.null_data && matches!(config.regex_mode, RegexMode::Basic | RegexMode::Extended) {
    options |= RegexOptions::REGEX_OPTION_MULTILINE;
}

Test

#[test]
fn null_data_anchors_are_record_anchors() {
    for args in [
        &["-z", "-c", "^beta"][..],
        &["-z", "-c", "-E", "alpha$"][..],
        &["-z", "-c", "-P", "beta$"][..],
    ] {
        let (_s, mut c) = ucmd();
        c.args(args)
            .pipe_in("alpha\nbeta\n\0")
            .fails_with_code(1)
            .stdout_only("0\n");
    }
    // Anchors at the record edges still work.
    let (_s, mut c) = ucmd();
    c.args(&["-z", "-c", "^alpha"])
        .pipe_in("alpha\nbeta\0")
        .succeeds()
        .stdout_only("1\n");
}

Exposed by the GNU grep test suite: z-anchor-newline, pcre.

Activity

  1. added
    bug
    gnu-compat
    good first issue
    on Nov 15, 2026
  2. ilainy commented on Nov 16, 2026

    @ilainy

    Hi, I'd like to work on this.

  3. sylvestre commented on Nov 16, 2026

    @sylvestre
    SponsorContributorAuthor

    Just submit a pr

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 issue

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions