Programming Search⌘K

Taskintro

Filter lines that match a pattern

Also called grep lines, select lines that match a regular expression, search a file for a pattern, grep -E.

Read a UTF-8 file and return each line in which a regular expression matches some part, in the order of the file, as grep -E does.

Task

Read a text file and a regular expression, and return the lines in which the regular expression matches. This is the job of grep. POSIX says that grep "shall search the input files, selecting lines matching one or more patterns".1 With -E, the pattern is an extended regular expression (ERE), and "If any entire ERE pattern matches some part of an input line excluding the terminating , the line shall be matched."1

The task needs three rules: what a line is, what the pattern can hold, and what a match is. This page uses these rules:

  • A line ends at LF. POSIX defines a line as "A sequence of zero or more non- characters plus a terminating character."2 The LF is not part of the line in the result, and the pattern does not see it. A CR before the LF stays in the line.
  • A last line with no LF is a line too. POSIX calls it an incomplete line: "A sequence of one or more non- characters at the end of the file."2
  • The pattern uses a small set of the syntax. A character that is not special matches itself. . matches any character. * after a character or . matches zero or more of it. ^ as the first character matches the start of the line, and $ as the last character matches the end of the line. The regular expressions of all the languages on this page agree on this set, so each solution can use the library of its language.
  • A match in some part of the line is enough. The pattern an matches banana. To match a whole line, put ^ at the start and $ at the end.
  • The result keeps the order and the duplicates. The lines that match come in the order of the file, and two equal lines that match are both in the result.

If the file does not exist, the solution reports an error.

Solutions

Each solution compiles the pattern one time, reads the file one line at a time, and keeps each line in which the pattern matches. The steps:

  1. Compile the pattern. If it is not valid, report an error.
  2. Read the next line, and remove the LF at its end.
  3. If the pattern matches some part of the line, add the line to the end of the result.
  4. At the end of the file, return the result.

The Python, Go, Rust, C++ and Bash solutions read one line at a time. The JavaScript, Java, C# and C solutions read the whole file into memory, and then split it.

  • Python. re.compile(pattern) compiles the pattern. open(path, encoding='utf-8', newline='\n') opens the file as text. With a value such as '\n', "input lines are only terminated by the given string, and the line ending is returned to the caller untranslated",3 so a CR stays in the line. line.removesuffix('\n') removes the LF. regex.search(line) does the match: it does a "Scan through string looking for the first location where the regular expression pattern produces a match".4
  • JavaScript and TypeScript (Node.js). readFileSync(path, 'utf8') reads the file, and split('\n') gives the lines. If the last part is empty, the code removes it. new RegExp(pattern, 'su') compiles the pattern. The s flag is necessary because, with no flag, . "Matches any single character except line terminators", and the list includes \r.5 "If the dotAll (s) flag is enabled, also matches line terminators."5 With the u flag, "Surrogate pairs will be interpreted as whole characters instead of two separate characters."6 regex.test(line) does the match. The TypeScript file adds types only.
  • Java. Pattern.compile(pattern, Pattern.UNIX_LINES) compiles the pattern. With no flag, Java treats a CR as a line terminator (see Pitfalls). With UNIX_LINES, "only the '\n' line terminator is recognized in the behavior of ., ^, and $."7 Files.readAllBytes(path) gives the bytes, and a loop splits them at each LF. regex.matcher(line).find() looks for a match in some part of the line.
  • C#. new Regex(pattern) compiles the pattern. File.ReadAllBytes(path) gives the bytes, Array.IndexOf finds each LF, and Encoding.UTF8.GetString decodes each line. regex.IsMatch(line) "Indicates whether the regular expression specified in the Regex constructor finds a match in a specified input string."8 By default, $ matches "at the end of the string or before \n at the end of the string",9 and a line has no LF, so $ matches only at the end of the line.
  • Go. regexp.Compile(pattern) compiles the pattern, which uses "the same general syntax used by Perl, Python, and other languages."10 bufio.Reader.ReadString('\n') reads each line, and strings.TrimSuffix removes the LF. re.MatchString(line) "reports whether the string s contains any match of the regular expression re."10 In Go, . is "any character, possibly including newline (flag s=true)",11 so it matches a CR.
  • Rust. The standard library has no regular expressions, so the solution has its own matcher for the set of this task. Brian Kernighan describes a matcher by Rob Pike for these constructs: "c matches any literal character c . matches any single character ^ matches the beginning of the input string $ matches the end of the input string * matches zero or more occurrences of the previous character".12 He says that this set "easily accounts for 95 percent of all instances" in his own use.12 The Rust code follows that matcher, on the char values of the line: matches tries each start in the line, match_here matches the pattern at one place, and match_star handles *. BufReader::read_line "Reads all bytes until a newline (the 0xA byte) is reached, and append them to the provided String buffer",13 so pop removes the LF at the end.
  • C. A loop of fread reads the file into a buffer that grows. The code changes each LF to a NUL, so each line is a C string. regcomp with REG_EXTENDED compiles the pattern as an ERE, and REG_NOSUB tells it to "Report only success/fail in regexec ()."14 For each line, regexec returns 0 if the line matches: "Upon successful completion, the regexec () function shall return 0. Otherwise, it shall return REG_NOMATCH to indicate no match."14 filter_lines fills a struct matched_lines, which the caller frees with matched_lines_free, or it returns -1 and sets errno.
  • C++. std::regex(pattern, std::regex::extended | std::regex::nosubs) compiles the pattern. The flag extended tells it to "Use the extended POSIX regular expression grammar".15 std::getline reads a binary std::ifstream one line at a time. std::regex_search "Determines if there is a match between the regular expression e and some subsequence in the target character sequence."16 The result is a std::expected (C++23), and the errors are cannot_open and read_failed.
  • Bash. LC_ALL=C grep -E -e PATTERN -- FILE does the work. The -e before the pattern tells grep that the next argument is the pattern, also when it starts with -. grep returns the status 1 when "No lines were selected",1 but for this task, no lines is a result, not an error (see Pitfalls). So the function returns 0 when the status is 0 or 1.

Edge cases

The cases are in cases/basic.jsonl and cases/edge.jsonl, with one file for each in fixtures/.

  • literal: the pattern an in apple, banana, cherry gives banana.
  • several: cat in cat, dog, catalog gives cat and catalog.
  • start and end: ^a in ab, ba gives ab, and a$ gives ba.
  • dot: a.c in abc, ac, axc gives abc and axc. The . must match one character, so ac does not match.
  • star: ab*c in ac, abc, abbc, adc gives ac, abc, abbc. Zero b is a match too.
  • whole-line: ^a$ in a, ab, ba gives a.
  • empty: an empty file gives [].
  • no-match: x in abc gives [].
  • empty-lines: ^$ in a, an empty line, b and an empty line gives two empty lines.
  • match-all: .* matches each line, also an empty line, because * can match zero characters.
  • duplicates: a in a, b, a gives a two times.
  • no-final-newline: b in a, LF, ab with no LF at the end gives ab.
  • crlf-end: b$ in ab CRLF and ab LF gives only the second ab. In the first line, the CR comes after the b.
  • crlf-dot: ^a.$ in a CRLF gives a CR. The . matches the CR.
  • case: apple in Apple, apple gives apple. The match is case sensitive.
  • non-ascii: é in café, cafe gives café.

The tests also write a file of 100000 lines with the numbers 0 to 99999. The pattern ^9*$ must give 9, 99, 999, 9999 and 99999. The case in cases/errors.jsonl must give the error not-found. The toolchain does not load that file yet, so each test file holds the case by name.

Pitfalls

  • The syntax is not the same in each language. C, C++ and grep -E use the POSIX ERE syntax. Python, JavaScript, Java, C# and Go use syntaxes that come from Perl. For the set of this task, they agree. In an ERE, . "shall match any character in the supported character set except NUL",17 and a character followed by * "shall match what zero or more consecutive occurrences of the ERE would match".17 Outside this set, the syntaxes are different. For example, \d is a digit in Python, JavaScript, Java, C# and Go, but it is not part of an ERE.
  • A CR can change $ in Java. With no flag, Java recognizes "A standalone carriage-return character" as a line terminator, and "The regular expression $ matches at the end of the entire input sequence, but also matches just before the last line terminator if this is not followed by any other input character."7 So b$ matches ab CR, and . does not match the CR. The Java solution uses UNIX_LINES, so the results are the same as in the other languages. In JavaScript, . does not match a CR unless the s flag is on.5
  • grep returns 1 when no line matches. POSIX gives three exit values: "0 One or more lines were selected", "1 No lines were selected", and ">1 An error occurred."1 In a script with set -e, the status 1 stops the script, and an empty result is not an error:
printf 'apple\nbanana\n' | grep -E 'an'
echo "status $?"
printf 'apple\nbanana\n' | grep -E 'x'
echo "status $?"
Output
banana
status 0
status 1
  • A g flag in JavaScript keeps state. "JavaScript RegExp objects are stateful when they have the global or sticky flags set", and "They store a lastIndex from the previous match."18 If the code calls test with the same /a/g on each line, the second call starts at the index after the first match, and it does not find the a. So the code skips lines that match. The solution does not use the g flag:
const lines = ["a", "a", "a"];
const global = /a/g;
console.log(lines.filter((line) => global.test(line)));
const plain = /a/;
console.log(lines.filter((line) => plain.test(line)));
Output
[ 'a', 'a' ]
[ 'a', 'a', 'a' ]
  • What . matches. A . matches one character, but code that works on bytes sees a character that is not ASCII as more than one byte. The letter é is two bytes in UTF-8, so ^caf.$ matches the text café, but not its UTF-8 bytes. The cases use . only with ASCII text:
import re

line = "caf\u00e9"
print(len(line), len(line.encode("utf-8")))
print(bool(re.search("^caf.$", line)))
print(bool(re.search(b"^caf.$", line.encode("utf-8"))))
Output
4 5
True
False
  • Text that holds special characters. If the pattern is plain text such as 1.5, the . matches any character, so 125 matches too. For plain text, use grep -F: "Treat each pattern specified as a string instead of a regular expression."1 In Python, re.escape does the same job: it does "Escape special characters in pattern".4

Code

The build runs the native tests of each language in a pinned toolchain.

filter_lines.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/filter-lines-that-match-a-pattern/.

"""Selects the lines of a text file that match a regular expression."""

import re
from os import PathLike


def filter_lines(path: str | PathLike[str], pattern: str) -> list[str]:
    """Returns the lines of the UTF-8 file at path that match pattern.

    A line matches if the pattern matches some part of it. A line ends at LF,
    and the LF is not part of it. A last line with no LF is a line too. Raises
    FileNotFoundError if the file does not exist, and re.error if the pattern
    is not valid.
    """
    regex = re.compile(pattern)
    # With newline="\n", only LF ends a line, and a CR stays in the line.
    with open(path, encoding="utf-8", newline="\n") as f:
        lines = (line.removesuffix("\n") for line in f)
        return [line for line in lines if regex.search(line)]
test_filter_lines.py 42 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/filter-lines-that-match-a-pattern/.

import pytest

from filter_lines import filter_lines

# name: (the bytes of the file, the pattern, the result)
CASES = {
    "literal": (b"apple\nbanana\ncherry\n", "an", ["banana"]),
    "several": (b"cat\ndog\ncatalog\n", "cat", ["cat", "catalog"]),
    "start": (b"ab\nba\n", "^a", ["ab"]),
    "end": (b"ab\nba\n", "a$", ["ba"]),
    "dot": (b"abc\nac\naxc\n", "a.c", ["abc", "axc"]),
    "star": (b"ac\nabc\nabbc\nadc\n", "ab*c", ["ac", "abc", "abbc"]),
    "whole-line": (b"a\nab\nba\n", "^a$", ["a"]),
    "empty": (b"", "a", []),
    "no-match": (b"abc\n", "x", []),
    "empty-lines": (b"a\n\nb\n\n", "^$", ["", ""]),
    "match-all": (b"a\n\nb\n", ".*", ["a", "", "b"]),
    "duplicates": (b"a\nb\na\n", "a", ["a", "a"]),
    "no-final-newline": (b"a\nab", "b", ["ab"]),
    "crlf-end": (b"ab\r\nab\n", "b$", ["ab"]),
    "crlf-dot": (b"a\r\n", "^a.$", ["a\r"]),
    "case": (b"Apple\napple\n", "apple", ["apple"]),
    "non-ascii": ("caf\u00e9\ncafe\n".encode(), "\u00e9", ["caf\u00e9"]),
    # 100000 lines with the numbers 0 to 99999. Five of them hold only nines.
    "many-lines": ("".join(f"{i}\n" for i in range(100000)).encode(), "^9*$", ["9", "99", "999", "9999", "99999"]),
}


@pytest.mark.parametrize("name", CASES)
def test_cases(tmp_path, name):
    data, pattern, expect = CASES[name]
    path = tmp_path / "input.txt"
    path.write_bytes(data)
    assert filter_lines(path, pattern) == expect


def test_not_found(tmp_path):
    with pytest.raises(FileNotFoundError):
        filter_lines(tmp_path / "missing.txt", "a")
filter_lines.cppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/filter-lines-that-match-a-pattern/.

#include "filter_lines.hpp"

#include <fstream>
#include <regex>

std::expected<std::vector<std::string>, FilterError> filter_lines(const std::filesystem::path& path,
                                                                  const std::string& pattern) {
    // std::regex::extended selects the POSIX extended syntax, as grep -E does.
    // nosubs asks only if the line matches, not where.
    const std::regex re(pattern, std::regex::extended | std::regex::nosubs);
    // Binary mode keeps each CR. In text mode, some systems change CRLF to LF.
    std::ifstream in(path, std::ios::binary);
    if (!in) {
        return std::unexpected(FilterError::cannot_open);
    }
    std::vector<std::string> lines;
    std::string line;
    // getline removes the LF. At the end of the file, it fails only if it
    // read no characters, so a last line with no LF is a line too.
    while (std::getline(in, line)) {
        // regex_search finds a match in some part of the line. regex_match
        // would need the whole line to match.
        if (std::regex_search(line, re)) {
            lines.push_back(line);
        }
    }
    if (in.bad()) {
        return std::unexpected(FilterError::read_failed);
    }
    return lines;
}
filter_lines.hpp 19 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/filter-lines-that-match-a-pattern/.
// since: C++23 (std::expected)

#pragma once

#include <expected>
#include <filesystem>
#include <string>
#include <vector>

enum class FilterError { cannot_open, read_failed };

// Returns the lines of the file at path that match pattern, a POSIX extended
// regular expression. A line matches if the pattern matches some part of it.
// A line ends at LF, and the LF is not part of it. A last line with no LF is a
// line too. A pattern that is not valid throws std::regex_error.
std::expected<std::vector<std::string>, FilterError> filter_lines(const std::filesystem::path& path,
                                                                  const std::string& pattern);
test_filter_lines.cpp 76 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/filter-lines-that-match-a-pattern/.

#include <cstdio>
#include <fstream>
#include <string>
#include <vector>

#include "filter_lines.hpp"

namespace {

const std::filesystem::path input = "filter_lines_input.txt";

void write(const std::string& data) {
    std::ofstream out(input, std::ios::binary);
    out.write(data.data(), static_cast<std::streamsize>(data.size()));
}

struct test_case {
    const char* name;
    std::string data;
    std::string pattern;
    std::vector<std::string> want;
};

}  // namespace

int main() {
    // 100000 lines with the numbers 0 to 99999. Five of them hold only nines.
    std::string numbers;
    for (int i = 0; i < 100000; i++) {
        numbers += std::to_string(i) + "\n";
    }

    const std::vector<test_case> cases = {
        {"literal", "apple\nbanana\ncherry\n", "an", {"banana"}},
        {"several", "cat\ndog\ncatalog\n", "cat", {"cat", "catalog"}},
        {"start", "ab\nba\n", "^a", {"ab"}},
        {"end", "ab\nba\n", "a$", {"ba"}},
        {"dot", "abc\nac\naxc\n", "a.c", {"abc", "axc"}},
        {"star", "ac\nabc\nabbc\nadc\n", "ab*c", {"ac", "abc", "abbc"}},
        {"whole-line", "a\nab\nba\n", "^a$", {"a"}},
        {"empty", "", "a", {}},
        {"no-match", "abc\n", "x", {}},
        {"empty-lines", "a\n\nb\n\n", "^$", {"", ""}},
        {"match-all", "a\n\nb\n", ".*", {"a", "", "b"}},
        {"duplicates", "a\nb\na\n", "a", {"a", "a"}},
        {"no-final-newline", "a\nab", "b", {"ab"}},
        {"crlf-end", "ab\r\nab\n", "b$", {"ab"}},
        {"crlf-dot", "a\r\n", "^a.$", {"a\r"}},
        {"case", "Apple\napple\n", "apple", {"apple"}},
        // U+00E9 is C3 A9.
        {"non-ascii", "caf\xc3\xa9\ncafe\n", "\xc3\xa9", {"caf\xc3\xa9"}},
        {"many-lines", numbers, "^9*$", {"9", "99", "999", "9999", "99999"}},
    };
    int failed = 0;
    for (const auto& c : cases) {
        write(c.data);
        auto got = filter_lines(input, c.pattern);
        if (!got || *got != c.want) {
            std::fprintf(stderr, "case %s failed\n", c.name);
            failed++;
        }
    }
    auto missing = filter_lines("no/such/dir/missing.txt", "a");
    if (missing || missing.error() != FilterError::cannot_open) {
        std::fprintf(stderr, "case not-found failed\n");
        failed++;
    }
    std::filesystem::remove(input);
    if (failed == 0) {
        std::puts("ok");
    }
    return failed == 0 ? 0 : 1;
}
MatchingLines.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/filter-lines-that-match-a-pattern/.

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

/** Selects the lines of a text file that match a regular expression. */
public final class MatchingLines {
  private MatchingLines() {}

  /**
   * Returns the lines of the UTF-8 file at path that match pattern. A line matches if the pattern
   * matches some part of it. A line ends at LF, and the LF is not part of it. A last line with no
   * LF is a line too.
   *
   * @throws java.nio.file.NoSuchFileException if the file does not exist
   * @throws java.util.regex.PatternSyntaxException if the pattern is not valid
   */
  public static List<String> read(Path path, String pattern) throws IOException {
    // Without UNIX_LINES, a CR is a line terminator too: $ matches before a CR
    // at the end of a line, and . does not match a CR.
    Pattern regex = Pattern.compile(pattern, Pattern.UNIX_LINES);
    byte[] data = Files.readAllBytes(path);
    List<String> lines = new ArrayList<>();
    int start = 0;
    while (start < data.length) {
      int end = start;
      while (end < data.length && data[end] != '\n') {
        end++;
      }
      String line = new String(data, start, end - start, StandardCharsets.UTF_8);
      // find looks for a match in some part of the line. matches would need the
      // whole line to match.
      if (regex.matcher(line).find()) {
        lines.add(line);
      }
      start = end + 1;
    }
    return lines;
  }
}
MatchingLinesTest.java 67 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/filter-lines-that-match-a-pattern/.

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.util.List;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

class MatchingLinesTest {
  @TempDir Path dir;

  // 100000 lines with the numbers 0 to 99999.
  private static String numbers() {
    StringBuilder b = new StringBuilder();
    for (int i = 0; i < 100000; i++) {
      b.append(i).append('\n');
    }
    return b.toString();
  }

  static Stream<Arguments> cases() {
    return Stream.of(
        Arguments.of("literal", "apple\nbanana\ncherry\n", "an", List.of("banana")),
        Arguments.of("several", "cat\ndog\ncatalog\n", "cat", List.of("cat", "catalog")),
        Arguments.of("start", "ab\nba\n", "^a", List.of("ab")),
        Arguments.of("end", "ab\nba\n", "a$", List.of("ba")),
        Arguments.of("dot", "abc\nac\naxc\n", "a.c", List.of("abc", "axc")),
        Arguments.of("star", "ac\nabc\nabbc\nadc\n", "ab*c", List.of("ac", "abc", "abbc")),
        Arguments.of("whole-line", "a\nab\nba\n", "^a$", List.of("a")),
        Arguments.of("empty", "", "a", List.of()),
        Arguments.of("no-match", "abc\n", "x", List.of()),
        Arguments.of("empty-lines", "a\n\nb\n\n", "^$", List.of("", "")),
        Arguments.of("match-all", "a\n\nb\n", ".*", List.of("a", "", "b")),
        Arguments.of("duplicates", "a\nb\na\n", "a", List.of("a", "a")),
        Arguments.of("no-final-newline", "a\nab", "b", List.of("ab")),
        Arguments.of("crlf-end", "ab\r\nab\n", "b$", List.of("ab")),
        Arguments.of("crlf-dot", "a\r\n", "^a.$", List.of("a\r")),
        Arguments.of("case", "Apple\napple\n", "apple", List.of("apple")),
        Arguments.of("non-ascii", "caf\u00e9\ncafe\n", "\u00e9", List.of("caf\u00e9")),
        // Five of the numbers hold only nines.
        Arguments.of("many-lines", numbers(), "^9*$", List.of("9", "99", "999", "9999", "99999")));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("cases")
  void read(String name, String text, String pattern, List<String> want) throws IOException {
    Path path = dir.resolve("input.txt");
    Files.writeString(path, text, StandardCharsets.UTF_8);
    assertEquals(want, MatchingLines.read(path, pattern), name);
  }

  @Test
  void notFound() {
    assertThrows(NoSuchFileException.class, () -> MatchingLines.read(dir.resolve("missing.txt"), "a"));
  }
}
filter_lines.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/filter-lines-that-match-a-pattern/.

#include "filter_lines.h"

#include <errno.h>
#include <regex.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>

// read_all reads the whole stream into a new buffer. The buffer has at least
// one free byte after the data, for a NUL.
static char *read_all(FILE *f, size_t *size) {
    size_t cap = 4096;
    size_t used = 0;
    char *data = malloc(cap);
    if (data == NULL) {
        errno = ENOMEM;
        return NULL;
    }
    for (;;) {
        if (cap - used < 2) {
            char *bigger = cap <= SIZE_MAX / 2 ? realloc(data, cap * 2) : NULL;
            if (bigger == NULL) {
                free(data);
                errno = ENOMEM;
                return NULL;
            }
            data = bigger;
            cap *= 2;
        }
        size_t n = fread(data + used, 1, cap - used - 1, f);
        used += n;
        if (n == 0) {
            break;
        }
    }
    if (ferror(f)) {
        free(data);
        errno = EIO;
        return NULL;
    }
    *size = used;
    return data;
}

int filter_lines(const char *path, const char *pattern, struct matched_lines *out) {
    // REG_EXTENDED selects the extended syntax, as grep -E does. REG_NOSUB
    // asks regexec only if the line matches, not where.
    regex_t re;
    if (regcomp(&re, pattern, REG_EXTENDED | REG_NOSUB) != 0) {
        errno = EINVAL;
        return -1;
    }
    FILE *f = fopen(path, "rb");
    if (f == NULL) {
        int e = errno;
        regfree(&re);
        errno = e;
        return -1;
    }
    size_t size;
    char *data = read_all(f, &size);
    int e = errno;
    fclose(f);
    if (data == NULL) {
        regfree(&re);
        errno = e;
        return -1;
    }
    // Each LF ends a line. A last line with no LF is one more line.
    size_t count = 0;
    for (size_t i = 0; i < size; i++) {
        count += data[i] == '\n';
    }
    if (size > 0 && data[size - 1] != '\n') {
        count++;
    }
    struct line *lines = count > 0 ? malloc(count * sizeof *lines) : NULL;
    if (count > 0 && lines == NULL) {
        regfree(&re);
        free(data);
        errno = ENOMEM;
        return -1;
    }
    // Change each LF to a NUL, so that each line is a C string, which is what
    // regexec takes. The end of the file ends a last line with no LF.
    size_t n = 0;
    size_t start = 0;
    for (size_t i = 0; i <= size; i++) {
        if (i < size ? data[i] != '\n' : start == size) {
            continue;
        }
        data[i] = '\0';
        if (regexec(&re, data + start, 0, NULL, 0) == 0) {
            lines[n++] = (struct line){data + start, i - start};
        }
        start = i + 1;
    }
    regfree(&re);
    *out = (struct matched_lines){lines, n, data};
    return 0;
}

void matched_lines_free(struct matched_lines *m) {
    free(m->lines);
    free(m->data);
    *m = (struct matched_lines){NULL, 0, NULL};
}
filter_lines.h 34 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/filter-lines-that-match-a-pattern/.

#ifndef FILTER_LINES_H
#define FILTER_LINES_H

#include <stddef.h>

// A line of the file: text is a C string with no LF, and len is its length.
struct line {
    const char *text;
    size_t len;
};

// The lines that matched. data holds all the bytes of the file, and each line
// points into it.
struct matched_lines {
    struct line *lines;
    size_t len;
    char *data;
};

// filter_lines reads the file at path and puts the lines that match pattern,
// a POSIX extended regular expression, into out. A line matches if the
// pattern matches some part of it. A line ends at LF, and the LF is not part
// of it. A last line with no LF is a line too. It returns 0, or -1 and sets
// errno: ENOENT if the file does not exist, EINVAL if the pattern is not
// valid.
int filter_lines(const char *path, const char *pattern, struct matched_lines *out);

// matched_lines_free frees the memory of the result.
void matched_lines_free(struct matched_lines *m);

#endif
test_filter_lines.c 97 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/filter-lines-that-match-a-pattern/.

#include "filter_lines.h"

#include <assert.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static const char *path = "filter_lines_input.txt";

static void write_file(const char *data, size_t n) {
    FILE *f = fopen(path, "wb");
    assert(f != NULL);
    assert(fwrite(data, 1, n, f) == n);
    assert(fclose(f) == 0);
}

static void check(const char *name, const char *data, size_t size, const char *pattern, const char *const *want,
                  size_t n) {
    write_file(data, size);
    struct matched_lines got;
    if (filter_lines(path, pattern, &got) != 0) {
        fprintf(stderr, "case %s: error %d\n", name, errno);
        exit(1);
    }
    if (got.len != n) {
        fprintf(stderr, "case %s: got %zu lines, want %zu\n", name, got.len, n);
        exit(1);
    }
    for (size_t i = 0; i < n; i++) {
        if (got.lines[i].len != strlen(want[i]) || strcmp(got.lines[i].text, want[i]) != 0) {
            fprintf(stderr, "case %s: line %zu is \"%s\", want \"%s\"\n", name, i, got.lines[i].text, want[i]);
            exit(1);
        }
    }
    matched_lines_free(&got);
}

// sizeof counts the bytes of the literal, but not the final NUL. The lines
// that the case wants come after the pattern.
#define CASE(name, data, pattern, ...)                                                    \
    do {                                                                                  \
        static const char *const want[] = {__VA_ARGS__};                                  \
        check(name, data, sizeof(data) - 1, pattern, want, sizeof want / sizeof want[0]); \
    } while (0)

int main(void) {
    CASE("literal", "apple\nbanana\ncherry\n", "an", "banana");
    CASE("several", "cat\ndog\ncatalog\n", "cat", "cat", "catalog");
    CASE("start", "ab\nba\n", "^a", "ab");
    CASE("end", "ab\nba\n", "a$", "ba");
    CASE("dot", "abc\nac\naxc\n", "a.c", "abc", "axc");
    CASE("star", "ac\nabc\nabbc\nadc\n", "ab*c", "ac", "abc", "abbc");
    CASE("whole-line", "a\nab\nba\n", "^a$", "a");
    check("empty", "", 0, "a", NULL, 0);
    check("no-match", "abc\n", 4, "x", NULL, 0);
    CASE("empty-lines", "a\n\nb\n\n", "^$", "", "");
    CASE("match-all", "a\n\nb\n", ".*", "a", "", "b");
    CASE("duplicates", "a\nb\na\n", "a", "a", "a");
    CASE("no-final-newline", "a\nab", "b", "ab");
    CASE("crlf-end", "ab\r\nab\n", "b$", "ab");
    CASE("crlf-dot", "a\r\n", "^a.$", "a\r");
    CASE("case", "Apple\napple\n", "apple", "apple");
    // U+00E9 is C3 A9.
    CASE("non-ascii", "caf\xc3\xa9\ncafe\n", "\xc3\xa9", "caf\xc3\xa9");

    // 100000 lines with the numbers 0 to 99999. Five of them hold only nines.
    size_t cap = 100000 * 6;
    char *data = malloc(cap);
    assert(data != NULL);
    size_t size = 0;
    for (int i = 0; i < 100000; i++) {
        size += (size_t)snprintf(data + size, cap - size, "%d\n", i);
    }
    write_file(data, size);
    free(data);
    struct matched_lines got;
    assert(filter_lines(path, "^9*$", &got) == 0);
    const char *nines[] = {"9", "99", "999", "9999", "99999"};
    assert(got.len == 5);
    for (size_t i = 0; i < got.len; i++) {
        assert(strcmp(got.lines[i].text, nines[i]) == 0);
    }
    matched_lines_free(&got);

    errno = 0;
    if (filter_lines("no/such/dir/missing.txt", "a", &got) != -1 || errno != ENOENT) {
        fprintf(stderr, "case not-found: want -1 and ENOENT\n");
        return 1;
    }
    remove(path);
    puts("ok");
    return 0;
}
MatchingLines.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/filter-lines-that-match-a-pattern/.

using System.Text;
using System.Text.RegularExpressions;

/// <summary>Selects the lines of a text file that match a regular expression.</summary>
public static class MatchingLines
{
    /// <summary>
    /// Returns the lines of the UTF-8 file at path that match pattern. A line matches if the
    /// pattern matches some part of it. A line ends at LF, and the LF is not part of it. A last
    /// line with no LF is a line too.
    /// </summary>
    /// <exception cref="FileNotFoundException">The file does not exist.</exception>
    /// <exception cref="ArgumentException">The pattern is not valid.</exception>
    public static List<string> Read(string path, string pattern)
    {
        var regex = new Regex(pattern);
        byte[] data = File.ReadAllBytes(path);
        var lines = new List<string>();
        int start = 0;
        while (start < data.Length)
        {
            int end = Array.IndexOf(data, (byte)'\n', start);
            if (end < 0)
            {
                end = data.Length;
            }
            string line = Encoding.UTF8.GetString(data, start, end - start);
            // IsMatch looks for a match in some part of the line.
            if (regex.IsMatch(line))
            {
                lines.Add(line);
            }
            start = end + 1;
        }
        return lines;
    }
}
MatchingLinesTests.cs 56 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/filter-lines-that-match-a-pattern/.

using System.Text;
using Xunit;

public sealed class MatchingLinesTests : IDisposable
{
    private readonly string dir = Directory.CreateTempSubdirectory("matching-lines-").FullName;

    public void Dispose() => Directory.Delete(dir, recursive: true);

    // 100000 lines with the numbers 0 to 99999.
    private static string Numbers() =>
        string.Concat(Enumerable.Range(0, 100000).Select(i => $"{i}\n"));

    public static TheoryData<string, string, string, string[]> Cases => new()
    {
        { "literal", "apple\nbanana\ncherry\n", "an", ["banana"] },
        { "several", "cat\ndog\ncatalog\n", "cat", ["cat", "catalog"] },
        { "start", "ab\nba\n", "^a", ["ab"] },
        { "end", "ab\nba\n", "a$", ["ba"] },
        { "dot", "abc\nac\naxc\n", "a.c", ["abc", "axc"] },
        { "star", "ac\nabc\nabbc\nadc\n", "ab*c", ["ac", "abc", "abbc"] },
        { "whole-line", "a\nab\nba\n", "^a$", ["a"] },
        { "empty", "", "a", [] },
        { "no-match", "abc\n", "x", [] },
        { "empty-lines", "a\n\nb\n\n", "^$", ["", ""] },
        { "match-all", "a\n\nb\n", ".*", ["a", "", "b"] },
        { "duplicates", "a\nb\na\n", "a", ["a", "a"] },
        { "no-final-newline", "a\nab", "b", ["ab"] },
        { "crlf-end", "ab\r\nab\n", "b$", ["ab"] },
        { "crlf-dot", "a\r\n", "^a.$", ["a\r"] },
        { "case", "Apple\napple\n", "apple", ["apple"] },
        { "non-ascii", "caf\u00e9\ncafe\n", "\u00e9", ["caf\u00e9"] },
        // Five of the numbers hold only nines.
        { "many-lines", Numbers(), "^9*$", ["9", "99", "999", "9999", "99999"] },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void Read(string name, string text, string pattern, string[] want)
    {
        string path = Path.Combine(dir, "input.txt");
        // UTF8Encoding(false) writes no byte order mark.
        File.WriteAllText(path, text, new UTF8Encoding(false));
        Assert.Equal(want, MatchingLines.Read(path, pattern));
        _ = name;
    }

    [Fact]
    public void NotFound()
    {
        Assert.Throws<FileNotFoundException>(() => MatchingLines.Read(Path.Combine(dir, "missing.txt"), "a"));
    }
}
filterLines.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/filter-lines-that-match-a-pattern/.

import { readFileSync } from "node:fs";

// Returns the lines of the UTF-8 file at path that match pattern, a regular
// expression. A line matches if the pattern matches some part of it. A line
// ends at LF, and the LF is not part of it. A last line with no LF is a line
// too. A missing file throws an error whose code is "ENOENT", and a pattern
// that is not valid throws a SyntaxError.
export function filterLines(path, pattern) {
  // With the s flag, . also matches CR. With the u flag, . matches one code
  // point, not one UTF-16 code unit. There is no g flag, so test() keeps no
  // state from one line to the next.
  const regex = new RegExp(pattern, "su");
  const lines = readFileSync(path, "utf8").split("\n");
  // The part after the last LF is empty, or it is a last line with no LF.
  if (lines.at(-1) === "") lines.pop();
  return lines.filter((line) => regex.test(line));
}
filterLines.test.js 49 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/filter-lines-that-match-a-pattern/.

import assert from "node:assert/strict";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { after, test } from "node:test";
import { filterLines } from "./filterLines.js";

const dir = mkdtempSync(join(tmpdir(), "filter-lines-"));
after(() => rmSync(dir, { recursive: true }));

const numbers = Array.from({ length: 100000 }, (_, i) => `${i}\n`).join("");

// [name, the text of the file, the pattern, the result]
const cases = [
  ["literal", "apple\nbanana\ncherry\n", "an", ["banana"]],
  ["several", "cat\ndog\ncatalog\n", "cat", ["cat", "catalog"]],
  ["start", "ab\nba\n", "^a", ["ab"]],
  ["end", "ab\nba\n", "a$", ["ba"]],
  ["dot", "abc\nac\naxc\n", "a.c", ["abc", "axc"]],
  ["star", "ac\nabc\nabbc\nadc\n", "ab*c", ["ac", "abc", "abbc"]],
  ["whole-line", "a\nab\nba\n", "^a$", ["a"]],
  ["empty", "", "a", []],
  ["no-match", "abc\n", "x", []],
  ["empty-lines", "a\n\nb\n\n", "^$", ["", ""]],
  ["match-all", "a\n\nb\n", ".*", ["a", "", "b"]],
  ["duplicates", "a\nb\na\n", "a", ["a", "a"]],
  ["no-final-newline", "a\nab", "b", ["ab"]],
  ["crlf-end", "ab\r\nab\n", "b$", ["ab"]],
  ["crlf-dot", "a\r\n", "^a.$", ["a\r"]],
  ["case", "Apple\napple\n", "apple", ["apple"]],
  ["non-ascii", "caf\u00e9\ncafe\n", "\u00e9", ["caf\u00e9"]],
  // 100000 lines with the numbers 0 to 99999. Five of them hold only nines.
  ["many-lines", numbers, "^9*$", ["9", "99", "999", "9999", "99999"]],
];

for (const [name, text, pattern, want] of cases) {
  test(name, () => {
    const path = join(dir, `${name}.txt`);
    writeFileSync(path, text, "utf8");
    assert.deepEqual(filterLines(path, pattern), want);
  });
}

test("not-found", () => {
  assert.throws(() => filterLines(join(dir, "missing.txt"), "a"), { code: "ENOENT" });
});
filterLines.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/filter-lines-that-match-a-pattern/.

import { readFileSync } from "node:fs";

// Returns the lines of the UTF-8 file at path that match pattern, a regular
// expression. A line matches if the pattern matches some part of it. A line
// ends at LF, and the LF is not part of it. A last line with no LF is a line
// too. A missing file throws an error whose code is "ENOENT", and a pattern
// that is not valid throws a SyntaxError.
export function filterLines(path: string, pattern: string): string[] {
  // With the s flag, . also matches CR. With the u flag, . matches one code
  // point, not one UTF-16 code unit. There is no g flag, so test() keeps no
  // state from one line to the next.
  const regex = new RegExp(pattern, "su");
  const lines = readFileSync(path, "utf8").split("\n");
  // The part after the last LF is empty, or it is a last line with no LF.
  if (lines.at(-1) === "") lines.pop();
  return lines.filter((line) => regex.test(line));
}
filterLines.test.ts 49 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/filter-lines-that-match-a-pattern/.

import assert from "node:assert/strict";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { after, test } from "node:test";
import { filterLines } from "./filterLines.ts";

const dir = mkdtempSync(join(tmpdir(), "filter-lines-"));
after(() => rmSync(dir, { recursive: true }));

const numbers = Array.from({ length: 100000 }, (_, i) => `${i}\n`).join("");

// [name, the text of the file, the pattern, the result]
const cases: [string, string, string, string[]][] = [
  ["literal", "apple\nbanana\ncherry\n", "an", ["banana"]],
  ["several", "cat\ndog\ncatalog\n", "cat", ["cat", "catalog"]],
  ["start", "ab\nba\n", "^a", ["ab"]],
  ["end", "ab\nba\n", "a$", ["ba"]],
  ["dot", "abc\nac\naxc\n", "a.c", ["abc", "axc"]],
  ["star", "ac\nabc\nabbc\nadc\n", "ab*c", ["ac", "abc", "abbc"]],
  ["whole-line", "a\nab\nba\n", "^a$", ["a"]],
  ["empty", "", "a", []],
  ["no-match", "abc\n", "x", []],
  ["empty-lines", "a\n\nb\n\n", "^$", ["", ""]],
  ["match-all", "a\n\nb\n", ".*", ["a", "", "b"]],
  ["duplicates", "a\nb\na\n", "a", ["a", "a"]],
  ["no-final-newline", "a\nab", "b", ["ab"]],
  ["crlf-end", "ab\r\nab\n", "b$", ["ab"]],
  ["crlf-dot", "a\r\n", "^a.$", ["a\r"]],
  ["case", "Apple\napple\n", "apple", ["apple"]],
  ["non-ascii", "caf\u00e9\ncafe\n", "\u00e9", ["caf\u00e9"]],
  // 100000 lines with the numbers 0 to 99999. Five of them hold only nines.
  ["many-lines", numbers, "^9*$", ["9", "99", "999", "9999", "99999"]],
];

for (const [name, text, pattern, want] of cases) {
  test(name, () => {
    const path = join(dir, `${name}.txt`);
    writeFileSync(path, text, "utf8");
    assert.deepEqual(filterLines(path, pattern), want);
  });
}

test("not-found", () => {
  assert.throws(() => filterLines(join(dir, "missing.txt"), "a"), { code: "ENOENT" });
});
filter_lines.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/filter-lines-that-match-a-pattern/.

// Package filterlines selects the lines of a text file that match a regular
// expression.
package filterlines

import (
	"bufio"
	"errors"
	"io"
	"os"
	"regexp"
	"strings"
)

// FilterLines returns the lines of the UTF-8 file at path that match pattern,
// a regular expression in the syntax of package regexp. A line matches if the
// pattern matches some part of it. A line ends at LF, and the LF is not part
// of it. A last line with no LF is a line too. A missing file gives an error
// that matches fs.ErrNotExist.
func FilterLines(path, pattern string) ([]string, error) {
	re, err := regexp.Compile(pattern)
	if err != nil {
		return nil, err
	}
	f, err := os.Open(path)
	if err != nil {
		return nil, err
	}
	defer f.Close()
	r := bufio.NewReader(f)
	lines := []string{}
	for {
		// ReadString returns the line with its LF, or the last line with no
		// LF together with io.EOF.
		line, err := r.ReadString('\n')
		if err != nil && !errors.Is(err, io.EOF) {
			return nil, err
		}
		if line != "" {
			line = strings.TrimSuffix(line, "\n")
			if re.MatchString(line) {
				lines = append(lines, line)
			}
		}
		if err != nil {
			return lines, nil
		}
	}
}
filter_lines_test.go 73 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/filter-lines-that-match-a-pattern/.

package filterlines

import (
	"errors"
	"io/fs"
	"os"
	"path/filepath"
	"reflect"
	"strconv"
	"strings"
	"testing"
)

// numbers returns 100000 lines with the numbers 0 to 99999.
func numbers() string {
	var b strings.Builder
	for i := 0; i < 100000; i++ {
		b.WriteString(strconv.Itoa(i) + "\n")
	}
	return b.String()
}

func TestFilterLines(t *testing.T) {
	cases := []struct {
		name, text, pattern string
		want                []string
	}{
		{"literal", "apple\nbanana\ncherry\n", "an", []string{"banana"}},
		{"several", "cat\ndog\ncatalog\n", "cat", []string{"cat", "catalog"}},
		{"start", "ab\nba\n", "^a", []string{"ab"}},
		{"end", "ab\nba\n", "a$", []string{"ba"}},
		{"dot", "abc\nac\naxc\n", "a.c", []string{"abc", "axc"}},
		{"star", "ac\nabc\nabbc\nadc\n", "ab*c", []string{"ac", "abc", "abbc"}},
		{"whole-line", "a\nab\nba\n", "^a$", []string{"a"}},
		{"empty", "", "a", []string{}},
		{"no-match", "abc\n", "x", []string{}},
		{"empty-lines", "a\n\nb\n\n", "^$", []string{"", ""}},
		{"match-all", "a\n\nb\n", ".*", []string{"a", "", "b"}},
		{"duplicates", "a\nb\na\n", "a", []string{"a", "a"}},
		{"no-final-newline", "a\nab", "b", []string{"ab"}},
		{"crlf-end", "ab\r\nab\n", "b$", []string{"ab"}},
		{"crlf-dot", "a\r\n", "^a.$", []string{"a\r"}},
		{"case", "Apple\napple\n", "apple", []string{"apple"}},
		{"non-ascii", "caf\u00e9\ncafe\n", "\u00e9", []string{"caf\u00e9"}},
		// Five of the numbers hold only nines.
		{"many-lines", numbers(), "^9*$", []string{"9", "99", "999", "9999", "99999"}},
	}
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			path := filepath.Join(t.TempDir(), "input.txt")
			if err := os.WriteFile(path, []byte(c.text), 0o644); err != nil {
				t.Fatal(err)
			}
			got, err := FilterLines(path, c.pattern)
			if err != nil {
				t.Fatal(err)
			}
			if !reflect.DeepEqual(got, c.want) {
				t.Errorf("got %q, want %q", got, c.want)
			}
		})
	}
}

func TestNotFound(t *testing.T) {
	_, err := FilterLines(filepath.Join(t.TempDir(), "missing.txt"), "a")
	if !errors.Is(err, fs.ErrNotExist) {
		t.Errorf("got %v, want fs.ErrNotExist", err)
	}
}
filter_lines.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/filter-lines-that-match-a-pattern/.

//! Selects the lines of a text file that match a small regular expression.

use std::fs::File;
use std::io::{self, BufRead, BufReader};
use std::path::Path;

/// Returns the lines of the UTF-8 file at `path` that match `pattern`. A line
/// matches if the pattern matches some part of it. A line ends at LF, and the
/// LF is not part of it. A last line with no LF is a line too. A missing file
/// gives an error of the kind `ErrorKind::NotFound`.
///
/// The standard library has no regular expressions, so the pattern is the
/// small set that `matches` knows: `c` matches the character c, `.` matches
/// any character, `^` at the start matches the start of the line, `$` at the
/// end matches the end of the line, and `*` matches zero or more of the
/// character before it.
pub fn filter_lines(path: impl AsRef<Path>, pattern: &str) -> io::Result<Vec<String>> {
    let pattern: Vec<char> = pattern.chars().collect();
    let mut reader = BufReader::new(File::open(path)?);
    let mut lines = Vec::new();
    let mut line = String::new();
    // read_line reads up to and with the next LF, so a CR stays in the line.
    // It returns 0 at the end of the file.
    while reader.read_line(&mut line)? > 0 {
        if line.ends_with('\n') {
            line.pop();
        }
        let text: Vec<char> = line.chars().collect();
        if matches(&pattern, &text) {
            lines.push(line.clone());
        }
        line.clear();
    }
    Ok(lines)
}

/// Reports whether `re` matches some part of `text`.
fn matches(re: &[char], text: &[char]) -> bool {
    if let ['^', rest @ ..] = re {
        return match_here(rest, text);
    }
    // Try each start, also the end of the text, where only an empty match is
    // possible.
    (0..=text.len()).any(|i| match_here(re, &text[i..]))
}

/// Reports whether `re` matches the start of `text`.
fn match_here(re: &[char], text: &[char]) -> bool {
    match re {
        [] => true,
        [c, '*', rest @ ..] => match_star(*c, rest, text),
        ['$'] => text.is_empty(),
        [c, rest @ ..] => match text {
            [t, text @ ..] if *c == '.' || c == t => match_here(rest, text),
            _ => false,
        },
    }
}

/// Reports whether zero or more `c`, then `re`, match the start of `text`.
fn match_star(c: char, re: &[char], text: &[char]) -> bool {
    let mut i = 0;
    loop {
        if match_here(re, &text[i..]) {
            return true;
        }
        if i < text.len() && (c == '.' || text[i] == c) {
            i += 1;
        } else {
            return false;
        }
    }
}
tests/filter_lines_test.rs 54 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/filter-lines-that-match-a-pattern/.

use std::fs;
use std::io::ErrorKind;
use std::path::PathBuf;

use algo_filter_lines::filter_lines;

fn temp_file(name: &str, text: &str) -> PathBuf {
    let dir = std::env::temp_dir().join(format!("filter-lines-{}", std::process::id()));
    fs::create_dir_all(&dir).unwrap();
    let path = dir.join(format!("{name}.txt"));
    fs::write(&path, text).unwrap();
    path
}

#[test]
fn cases() {
    // 100000 lines with the numbers 0 to 99999. Five of them hold only nines.
    let numbers: String = (0..100000).map(|i| format!("{i}\n")).collect();
    let cases: &[(&str, &str, &str, &[&str])] = &[
        ("literal", "apple\nbanana\ncherry\n", "an", &["banana"]),
        ("several", "cat\ndog\ncatalog\n", "cat", &["cat", "catalog"]),
        ("start", "ab\nba\n", "^a", &["ab"]),
        ("end", "ab\nba\n", "a$", &["ba"]),
        ("dot", "abc\nac\naxc\n", "a.c", &["abc", "axc"]),
        ("star", "ac\nabc\nabbc\nadc\n", "ab*c", &["ac", "abc", "abbc"]),
        ("whole-line", "a\nab\nba\n", "^a$", &["a"]),
        ("empty", "", "a", &[]),
        ("no-match", "abc\n", "x", &[]),
        ("empty-lines", "a\n\nb\n\n", "^$", &["", ""]),
        ("match-all", "a\n\nb\n", ".*", &["a", "", "b"]),
        ("duplicates", "a\nb\na\n", "a", &["a", "a"]),
        ("no-final-newline", "a\nab", "b", &["ab"]),
        ("crlf-end", "ab\r\nab\n", "b$", &["ab"]),
        ("crlf-dot", "a\r\n", "^a.$", &["a\r"]),
        ("case", "Apple\napple\n", "apple", &["apple"]),
        ("non-ascii", "caf\u{e9}\ncafe\n", "\u{e9}", &["caf\u{e9}"]),
        ("many-lines", &numbers, "^9*$", &["9", "99", "999", "9999", "99999"]),
    ];
    for (name, text, pattern, want) in cases {
        let path = temp_file(name, text);
        let got = filter_lines(&path, pattern).unwrap();
        assert_eq!(got, *want, "case {name}");
        fs::remove_file(path).unwrap();
    }
}

#[test]
fn not_found() {
    let err = filter_lines("no/such/dir/missing.txt", "a").unwrap_err();
    assert_eq!(err.kind(), ErrorKind::NotFound);
}
filter_lines.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/filter-lines-that-match-a-pattern/.

# filter_lines PATH PATTERN
# Prints the lines of the file at PATH that match PATTERN, a POSIX extended
# regular expression, each with an LF at the end. Returns a nonzero status,
# and prints nothing on stdout, if the file cannot be read or the pattern is
# not valid.
filter_lines() {
  [[ -r $1 && ! -d $1 ]] || { printf 'filter_lines: cannot read %s\n' "$1" >&2; return 1; }
  # -e marks the pattern, so a pattern that starts with - is not an option.
  # LC_ALL=C selects the POSIX locale, so the locale of the user does not
  # change the result.
  local status=0
  LC_ALL=C grep -E -e "$2" -- "$1" || status=$?
  # grep returns 1 if no line matched. For this function, that is not an
  # error: the result is no lines.
  ((status <= 1))
}
test_filter_lines.bats 46 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/filter-lines-that-match-a-pattern/.

bats_require_minimum_version 1.5.0

setup() {
  source "$BATS_TEST_DIRNAME/filter_lines.sh"
  file="$BATS_TEST_TMPDIR/input.txt"
}

check() { # check BYTES PATTERN WANT
  printf '%b' "$1" >"$file"
  # The x keeps the final LFs, which $(...) removes.
  got=$(filter_lines "$file" "$2" && printf x)
  [ "$got" = "$(printf '%bx' "$3")" ]
}

@test "literal" { check 'apple\nbanana\ncherry\n' 'an' 'banana\n'; }
@test "several" { check 'cat\ndog\ncatalog\n' 'cat' 'cat\ncatalog\n'; }
@test "start" { check 'ab\nba\n' '^a' 'ab\n'; }
@test "end" { check 'ab\nba\n' 'a$' 'ba\n'; }
@test "dot" { check 'abc\nac\naxc\n' 'a.c' 'abc\naxc\n'; }
@test "star" { check 'ac\nabc\nabbc\nadc\n' 'ab*c' 'ac\nabc\nabbc\n'; }
@test "whole-line" { check 'a\nab\nba\n' '^a$' 'a\n'; }
@test "empty" { check '' 'a' ''; }
@test "no-match" { check 'abc\n' 'x' ''; }
@test "empty-lines" { check 'a\n\nb\n\n' '^$' '\n\n'; }
@test "match-all" { check 'a\n\nb\n' '.*' 'a\n\nb\n'; }
@test "duplicates" { check 'a\nb\na\n' 'a' 'a\na\n'; }
@test "no-final-newline" { check 'a\nab' 'b' 'ab\n'; }
@test "crlf-end" { check 'ab\r\nab\n' 'b$' 'ab\n'; }
@test "crlf-dot" { check 'a\r\n' '^a.$' 'a\r\n'; }
@test "case" { check 'Apple\napple\n' 'apple' 'apple\n'; }
@test "non-ascii" { check 'caf\xc3\xa9\ncafe\n' "$(printf '\xc3\xa9')" 'caf\xc3\xa9\n'; }

@test "many-lines" {
  seq 0 99999 >"$file"
  [ "$(filter_lines "$file" '^9*$')" = "$(printf '9\n99\n999\n9999\n99999')" ]
}

@test "not-found" {
  run filter_lines "$BATS_TEST_TMPDIR/missing.txt" a
  [ "$status" -ne 0 ]
  [ "$output" = "filter_lines: cannot read $BATS_TEST_TMPDIR/missing.txt" ]
}

References

  1. The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), grep, DESCRIPTION; OPTIONS (-E, -F); EXIT STATUS
  2. The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), Base Definitions, Chapter 3, Definitions, 3.172 Incomplete Line; 3.185 Line
  3. The Python Standard Library, Built-in Functions, open (newline)
  4. The Python Standard Library, re, Regular expression syntax; re.search; re.escape
  5. MDN Web Docs, Character classes, Wildcard
  6. MDN Web Docs, RegExp.prototype.unicode, Description
  7. Java SE 25 API, java.util.regex.Pattern, Line terminators; UNIX_LINES
  8. .NET API reference, Regex.IsMatch
  9. .NET documentation, Anchors in regular expressions
  10. Go standard library, package regexp, Overview; Regexp.MatchString
  11. Go standard library, package regexp/syntax, Syntax
  12. A Regular Expression Matcher, code by Rob Pike, exegesis by Brian Kernighan, The Practice of Programming
  13. The Rust Standard Library, std::io::BufRead, read_line
  14. The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), regcomp, regexec, DESCRIPTION; RETURN VALUE
  15. cppreference.com, std::regex_constants::syntax_option_type
  16. cppreference.com, std::regex_search
  17. The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), Base Definitions, Chapter 9, Regular Expressions, 9.4.4 Periods in EREs; 9.4.6 EREs Matching Multiple Characters; 9.4.9 ERE Expression Anchoring
  18. MDN Web Docs, RegExp.prototype.test(), Description

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (bash)I0 not checked yet
  • the tests did not run in this build
Code (c)I0 not checked yet
  • the tests did not run in this build
Code (cpp)I0 not checked yet
  • the tests did not run in this build
Code (csharp)I0 not checked yet
  • the tests did not run in this build
Code (go)I0 not checked yet
  • the tests did not run in this build
Code (java)I0 not checked yet
  • the tests did not run in this build
Code (javascript)I0 not checked yet
  • the tests did not run in this build
Code (python)I0 not checked yet
  • the tests did not run in this build
Code (rust)I0 not checked yet
  • the tests did not run in this build
Code (typescript)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source