Programming Search⌘K

Taskintro

Remove duplicate lines

Also called deduplicate lines, keep the first copy of each line, remove duplicate lines without sorting, awk '!seen[$0]++'.

Read a UTF-8 file and return its lines with only the first copy of each line, in the order of the file, with a set of the lines that were seen, as awk '!seen[$0]++' does.

Task

Read a text file and return its lines, with only the first copy of each line. The lines stay in the order of the file. The uniq utility does not do this job alone. POSIX says that uniq shall "read an input file comparing adjacent lines, and write one copy of each input line on the output", but also that "Repeated lines in the input shall not be detected if they are not adjacent."1

The task needs three rules: what a line is, when two lines are equal, and which copy stays. 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. A CR before the LF stays in the line, so a CRLF and a LF are two different lines.
  • 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 So the file a, LF, b, LF, a gives two lines, a and b.
  • Two lines are equal if their bytes are equal. The solutions do not ignore case, do not remove spaces, and do not normalize Unicode text. So A and a are two lines, and a and a with a space at the end are two lines.
  • The first copy stays, at its place. The result has the lines in the order of their first copies. So b, a, b, c, a gives b, a, c.
  • An empty line is a line. Two empty lines are equal, so only the first one stays. An empty file gives no lines.

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

Solutions

Each solution keeps a set of the lines that it has seen. It reads the lines in order, and it keeps a line only if the set does not have it. The steps:

  1. Read the next line, and remove the LF at its end.
  2. If the set has the line, go to step 1.
  3. Add the line to the set and to the end of the result.
  4. At the end of the file, return the result.

The set is a hash set, so the solution does not compare each line with all the lines before it. The memory grows with the number of different lines, not with the number of lines. The Python, Go, Rust and C++ 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. open(path, 'rb') opens the file in binary mode. For binary files, "The line terminator is always b'\n'",3 so a loop on the file gives each line with its LF, and a CR stays in the line. line.removesuffix(b'\n') removes the LF. dict.fromkeys makes a dictionary that has the lines as its keys. A line that comes again does not move its key: "Dictionaries preserve insertion order. Note that updating a key does not affect the order."4 The solution then decodes each key as UTF-8.
  • JavaScript and TypeScript (Node.js). readFileSync(path) gives a Buffer. A loop with indexOf(0x0a, start) finds each LF, and toString('utf8', start, end) decodes each line. A Set keeps the lines. MDN says: "You can iterate through the elements of a set in insertion order. The insertion order corresponds to the order in which each element was inserted into the set by the add() method successfully (that is, there wasn't an identical element already in the set when add() was called)."5 So [...unique] gives the first copies in order. The TypeScript file adds types only.
  • Java. Files.readAllBytes(path) gives the bytes. A loop finds each LF, and new String(data, start, length, StandardCharsets.UTF_8) decodes each line. A LinkedHashSet<String> keeps the lines in the order in which they were added: "Note that encounter order is not affected if an element is re-inserted into the set with the add method."6 new ArrayList<>(lines) copies them to a list.
  • C#. File.ReadAllBytes(path) gives the bytes. Array.IndexOf finds each LF, and Encoding.UTF8.GetString decodes each line. A HashSet<string> with StringComparer.Ordinal keeps the lines that were seen, and Add returns "true if the element is added to the HashSet<T> object; false if the element is already present."7 A HashSet<T> has no order, so a List<string> keeps the result, and the solution adds a line to it only when Add returns true.
  • Go. bufio.Reader.ReadString('\n') "reads until the first occurrence of delim in the input, returning a string containing the data up to and including the delimiter."8 At the end of the file, it "returns the data read before the error and the error itself (often io.EOF)",8 so a last line with no LF comes with io.EOF. strings.TrimSuffix removes the LF. A map[string]bool keeps the lines that were seen, and a slice keeps the result.
  • Rust. BufReader::read_line "Reads all bytes until a newline (the 0xA byte) is reached, and append them to the provided String buffer."9 It returns Ok(0) at the end of the file, and it returns an error "if the read bytes are not valid UTF-8".9 The solution removes the LF with pop. A HashSet<String> keeps the lines that were seen. contains takes a &str, so a duplicate line is not copied. For a new line, insert puts a copy in the set, and std::mem::take moves the line into the result. insert "Returns whether the value was newly inserted."10
  • 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 in the buffer. The C standard library has no set, so the code has a small hash table: an array of slots, where each slot holds 0 or the index of a line plus 1. A collision goes to the next slot. When the table is half full, the code makes a table of double the size and puts the lines into it again. remove_duplicate_lines fills a struct unique_lines, which the caller frees with unique_lines_free, or it returns -1 and sets errno.
  • C++. std::getline reads a binary std::ifstream one line at a time. The LF "is extracted from input, but is not appended to str".11 At the end of the file: "If no characters were extracted for whatever reason (not even the discarded delimiter), getline sets failbit and returns."11 So the loop also reads a last line with no LF, and then it stops. std::unordered_set<std::string>::insert returns a pair, and its second value is "a bool value set to true if and only if the insertion took place."12 The result is a std::expected (C++23), and the errors are cannot_open and read_failed.
  • Bash. LC_ALL=C awk '!seen[$0]++' on the file does the work. POSIX says: "By default, a record is a line, less its terminating ".13 seen is an array, and its "subscripts, or element identifiers, are strings, providing a type of associative array capability."13 The first time that awk reads a line, seen[$0] has no value, and "An uninitialized value shall have both a numeric value of zero and a string value of the empty string."13 The post-increment ++ gives the old value, 0, and then adds 1. So !seen[$0]++ is true only for the first copy. The pattern has no action, and "a missing action shall be equivalent to: { print }".13 print writes ORS after the line, and ORS is "a by default",13 so each line of the output ends with an LF, also the last one.

Edge cases

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

  • simple: b, a, b, c, a gives b, a, c. Each line stays at the place of its first copy.
  • adjacent: a, a, b gives a, b.
  • no-duplicates: c, b, a gives c, b, a. The order does not change.
  • empty: an empty file gives [].
  • empty-lines: an empty line, a, and two empty lines give "" and a.
  • all-same: x, x, x gives x.
  • no-final-newline: a, LF, b, LF, a with no LF at the end gives a and b. The last a is a line, and it is a copy of the first line.
  • crlf: a CRLF a LF gives a CR and a. The CR stays, so the two lines are not equal.
  • case: A, a, A gives A, a.
  • whitespace: a space, a, space a, a space gives a space, a, space a.
  • normalization: U+00E9, then e and U+0301, then U+00E9 gives U+00E9 and e U+0301. The two lines look the same, but their bytes are not equal.

The tests also write a file of 100000 lines, with the numbers 0 to 999 one after the other, 100 times. The result must be the 1000 lines 0 to 999. 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

  • uniq removes only adjacent duplicates. "Repeated lines in the input shall not be detected if they are not adjacent."1 So uniq alone does not remove a duplicate line that comes later in the file. sort -u removes all the duplicates, "Unique: suppress all but one in each set of lines having equal keys",14 but the result is in sorted order, not in the order of the file. Only the awk program keeps the first copies in their order:
printf 'b\na\nb\n' | uniq | paste -s -d ' ' -
printf 'b\na\nb\n' | LC_ALL=C sort -u | paste -s -d ' ' -
printf 'b\na\nb\n' | awk '!seen[$0]++' | paste -s -d ' ' -
Output
b a b
a b
b a
  • Text mode can change the lines. In Python text mode with the default newline, "Lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n' before being returned to the caller."3 So a CRLF and a LF become the same line. With newline='', the line ends stay, and the two lines are different. In both modes, a CR alone also ends a line. The solution opens the file in binary mode, where the LF is the only line end:
import io

data = b"a\r\na\n"
for newline in (None, ""):
    f = io.TextIOWrapper(io.BytesIO(data), encoding="utf-8", newline=newline)
    lines = [line.removesuffix("\n") for line in f]
    print(repr(newline), list(dict.fromkeys(lines)))
Output
None ['a']
'' ['a\r', 'a']
  • Lines that look the same can be different. In Unicode, "two sequences of code points have canonical equivalence if they represent the same abstract characters, and should always have the same visual appearance and behavior".15 U+00E9 and e with U+0301 are canonically equivalent, but their code points are not equal, so the solutions keep both lines. If the task must treat them as equal, normalize each line before the set check. normalize() "returns the Unicode Normalization Form of this string":15
// U+00E9, and e with the combining acute accent U+0301.
const lines = ["\u00e9", "e\u0301"];
console.log(lines[0] === lines[1]);
console.log(new Set(lines).size);
console.log(new Set(lines.map((line) => line.normalize("NFC"))).size);
Output
false
2
1
  • Case and spaces. The solutions compare the bytes, so A and a are two lines, and so are a and a with a space at the end. To ignore case or spaces, put a key in the set, for example the line in lowercase with no spaces at the ends, but put the line itself in the result.
  • Memory. The set holds a copy of each different line. If most of the lines are different, the set needs about as much memory as the file. If the order of the result is not important, LC_ALL=C sort -u gives the same lines in sorted order.

Code

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

remove_duplicate_lines.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/remove-duplicate-lines/.

"""Removes the duplicate lines of a text file."""

from os import PathLike


def remove_duplicate_lines(path: str | PathLike[str]) -> list[str]:
    """Returns the lines of the UTF-8 file at path, each one only once.

    Each line stays at the place of its first copy. A line ends at LF, and the
    LF is not part of it. A last line with no LF is a line too. Memory grows
    with the different lines, not with the size of the file. Raises
    FileNotFoundError if the file does not exist.
    """
    with open(path, "rb") as f:
        # A file in binary mode splits lines at LF only, and keeps each CR.
        # dict.fromkeys keeps the first copy of each line, at its first place.
        unique = dict.fromkeys(line.removesuffix(b"\n") for line in f)
    return [line.decode("utf-8") for line in unique]
test_remove_duplicate_lines.py 37 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/remove-duplicate-lines/.

import pytest

from remove_duplicate_lines import remove_duplicate_lines

# name: (the bytes of the file, the result)
CASES = {
    "simple": (b"b\na\nb\nc\na\n", ["b", "a", "c"]),
    "adjacent": (b"a\na\nb\n", ["a", "b"]),
    "no-duplicates": (b"c\nb\na\n", ["c", "b", "a"]),
    "empty": (b"", []),
    "empty-lines": (b"\na\n\n\n", ["", "a"]),
    "all-same": (b"x\nx\nx\n", ["x"]),
    "no-final-newline": (b"a\nb\na", ["a", "b"]),
    "crlf": (b"a\r\na\n", ["a\r", "a"]),
    "case": (b"A\na\nA\n", ["A", "a"]),
    "whitespace": (b"a \na\n a\na \n", ["a ", "a", " a"]),
    # U+00E9, then e and U+0301: the same letter, but not the same code points.
    "normalization": ("\u00e9\ne\u0301\n\u00e9\n".encode(), ["\u00e9", "e\u0301"]),
    # 100000 lines with 1000 different lines.
    "many-lines": ("".join(f"{i % 1000}\n" for i in range(100000)).encode(), [str(i) for i in range(1000)]),
}


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


def test_not_found(tmp_path):
    with pytest.raises(FileNotFoundError):
        remove_duplicate_lines(tmp_path / "missing.txt")
remove_duplicate_lines.cppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-duplicate-lines/.

#include "remove_duplicate_lines.hpp"

#include <fstream>
#include <unordered_set>

std::expected<std::vector<std::string>, DedupError> remove_duplicate_lines(const std::filesystem::path& path) {
    // 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(DedupError::cannot_open);
    }
    std::unordered_set<std::string> seen;
    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)) {
        // insert returns false as its second value if the set has the line.
        if (seen.insert(line).second) {
            lines.push_back(line);
        }
    }
    if (in.bad()) {
        return std::unexpected(DedupError::read_failed);
    }
    return lines;
}
remove_duplicate_lines.hpp 18 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-duplicate-lines/.
// since: C++23 (std::expected)

#pragma once

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

enum class DedupError { cannot_open, read_failed };

// Returns the lines of the file at path, with only the first copy of each
// line, in the order of the file. Two lines are equal if their bytes are
// equal. A line ends at LF, and the LF is not part of it. A last line with no
// LF is a line too.
std::expected<std::vector<std::string>, DedupError> remove_duplicate_lines(const std::filesystem::path& path);
test_remove_duplicate_lines.cpp 73 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-duplicate-lines/.

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

#include "remove_duplicate_lines.hpp"

namespace {

const std::filesystem::path input = "remove_duplicate_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::vector<std::string> want;
};

}  // namespace

int main() {
    // 100000 lines with 1000 different lines.
    std::string many;
    std::vector<std::string> many_want;
    for (int i = 0; i < 100000; i++) {
        many += std::to_string(i % 1000) + "\n";
    }
    for (int i = 0; i < 1000; i++) {
        many_want.push_back(std::to_string(i));
    }

    const std::vector<test_case> cases = {
        {"simple", "b\na\nb\nc\na\n", {"b", "a", "c"}},
        {"adjacent", "a\na\nb\n", {"a", "b"}},
        {"no-duplicates", "c\nb\na\n", {"c", "b", "a"}},
        {"empty", "", {}},
        {"empty-lines", "\na\n\n\n", {"", "a"}},
        {"all-same", "x\nx\nx\n", {"x"}},
        {"no-final-newline", "a\nb\na", {"a", "b"}},
        {"crlf", "a\r\na\n", {"a\r", "a"}},
        {"case", "A\na\nA\n", {"A", "a"}},
        {"whitespace", "a \na\n a\na \n", {"a ", "a", " a"}},
        // U+00E9 is C3 A9. e and U+0301 is 65 CC 81.
        {"normalization", "\xc3\xa9\ne\xcc\x81\n\xc3\xa9\n", {"\xc3\xa9", "e\xcc\x81"}},
        {"many-lines", many, many_want},
    };
    int failed = 0;
    for (const auto& c : cases) {
        write(c.data);
        auto got = remove_duplicate_lines(input);
        if (!got || *got != c.want) {
            std::fprintf(stderr, "case %s failed\n", c.name);
            failed++;
        }
    }
    auto missing = remove_duplicate_lines("no/such/dir/missing.txt");
    if (missing || missing.error() != DedupError::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;
}
UniqueLines.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-duplicate-lines/.

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.LinkedHashSet;
import java.util.List;
import java.util.Set;

/** Removes the duplicate lines of a text file. */
public final class UniqueLines {
  private UniqueLines() {}

  /**
   * Returns the lines of the UTF-8 file at path, with only the first copy of each line, in the
   * order of the file. 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
   */
  public static List<String> read(Path path) throws IOException {
    byte[] data = Files.readAllBytes(path);
    // A LinkedHashSet keeps the order in which the lines were added first. If
    // a line is added again, the set does not change.
    Set<String> lines = new LinkedHashSet<>();
    int start = 0;
    while (start < data.length) {
      int end = start;
      while (end < data.length && data[end] != '\n') {
        end++;
      }
      lines.add(new String(data, start, end - start, StandardCharsets.UTF_8));
      start = end + 1;
    }
    return new ArrayList<>(lines);
  }
}
UniqueLinesTest.java 70 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-duplicate-lines/.

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.ArrayList;
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 UniqueLinesTest {
  @TempDir Path dir;

  // 100000 lines with 1000 different lines.
  private static String manyLines() {
    StringBuilder b = new StringBuilder();
    for (int i = 0; i < 100000; i++) {
      b.append(i % 1000).append('\n');
    }
    return b.toString();
  }

  private static List<String> numbers(int n) {
    List<String> lines = new ArrayList<>(n);
    for (int i = 0; i < n; i++) {
      lines.add(Integer.toString(i));
    }
    return lines;
  }

  static Stream<Arguments> cases() {
    return Stream.of(
        Arguments.of("simple", "b\na\nb\nc\na\n", List.of("b", "a", "c")),
        Arguments.of("adjacent", "a\na\nb\n", List.of("a", "b")),
        Arguments.of("no-duplicates", "c\nb\na\n", List.of("c", "b", "a")),
        Arguments.of("empty", "", List.of()),
        Arguments.of("empty-lines", "\na\n\n\n", List.of("", "a")),
        Arguments.of("all-same", "x\nx\nx\n", List.of("x")),
        Arguments.of("no-final-newline", "a\nb\na", List.of("a", "b")),
        Arguments.of("crlf", "a\r\na\n", List.of("a\r", "a")),
        Arguments.of("case", "A\na\nA\n", List.of("A", "a")),
        Arguments.of("whitespace", "a \na\n a\na \n", List.of("a ", "a", " a")),
        // U+00E9 and e with U+0301 look the same, but their code points are not equal.
        Arguments.of("normalization", "\u00e9\ne\u0301\n\u00e9\n", List.of("\u00e9", "e\u0301")),
        Arguments.of("many-lines", manyLines(), numbers(1000)));
  }

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

  @Test
  void notFound() {
    assertThrows(NoSuchFileException.class, () -> UniqueLines.read(dir.resolve("missing.txt")));
  }
}
remove_duplicate_lines.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-duplicate-lines/.

#include "remove_duplicate_lines.h"

#include <errno.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.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;
}

// hash is the 64-bit FNV-1a hash of the bytes of a line.
static uint64_t hash(const char *s, size_t n) {
    uint64_t h = 14695981039346656037u;
    for (size_t i = 0; i < n; i++) {
        h = (h ^ (unsigned char)s[i]) * 1099511628211u;
    }
    return h;
}

// A set of lines: an open addressing table with linear probing. Each slot
// holds 0 for an empty slot, or 1 plus the index of a line in lines.
struct set {
    size_t *slots;
    size_t cap;  // a power of 2
};

static bool same(const struct line *a, const struct line *b) {
    return a->len == b->len && memcmp(a->text, b->text, a->len) == 0;
}

// find returns the slot of the line, or the empty slot where it belongs.
static size_t find(const struct set *s, const struct line *lines, const struct line *l) {
    size_t i = (size_t)(hash(l->text, l->len) & (s->cap - 1));
    while (s->slots[i] != 0 && !same(&lines[s->slots[i] - 1], l)) {
        i = (i + 1) & (s->cap - 1);
    }
    return i;
}

// grow doubles the table and puts the n lines into it again.
static int grow(struct set *s, const struct line *lines, size_t n) {
    struct set bigger = {calloc(s->cap * 2, sizeof(size_t)), s->cap * 2};
    if (bigger.slots == NULL) {
        return -1;
    }
    for (size_t k = 0; k < n; k++) {
        bigger.slots[find(&bigger, lines, &lines[k])] = k + 1;
    }
    free(s->slots);
    *s = bigger;
    return 0;
}

int remove_duplicate_lines(const char *path, struct unique_lines *out) {
    FILE *f = fopen(path, "rb");
    if (f == NULL) {
        return -1;
    }
    size_t size;
    char *data = read_all(f, &size);
    fclose(f);
    if (data == NULL) {
        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;
    struct set set = {calloc(16, sizeof(size_t)), 16};
    if ((count > 0 && lines == NULL) || set.slots == NULL) {
        free(lines);
        free(set.slots);
        free(data);
        errno = ENOMEM;
        return -1;
    }
    // Change each LF to a NUL, so that each line is a C string too. The end
    // of the file ends a last line with no LF. Keep a line only if the set
    // does not have it yet.
    size_t n = 0;
    size_t start = 0;
    for (size_t i = 0; i <= size; i++) {
        bool end = i < size ? data[i] == '\n' : start < size;
        if (!end) {
            continue;
        }
        data[i] = '\0';
        struct line l = {data + start, i - start};
        start = i + 1;
        size_t slot = find(&set, lines, &l);
        if (set.slots[slot] != 0) {
            continue;
        }
        lines[n++] = l;
        set.slots[slot] = n;
        // Keep the table less than half full, so that a probe ends soon.
        if (2 * n > set.cap && grow(&set, lines, n) != 0) {
            free(lines);
            free(set.slots);
            free(data);
            errno = ENOMEM;
            return -1;
        }
    }
    free(set.slots);
    *out = (struct unique_lines){lines, n, data};
    return 0;
}

void unique_lines_free(struct unique_lines *u) {
    free(u->lines);
    free(u->data);
    *u = (struct unique_lines){NULL, 0, NULL};
}
remove_duplicate_lines.h 30 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-duplicate-lines/.

#ifndef REMOVE_DUPLICATE_LINES_H
#define REMOVE_DUPLICATE_LINES_H

#include <stddef.h>

struct line {
    const char *text;  // the bytes of the line, with no LF, ended by a NUL
    size_t len;        // the number of bytes, not counting the NUL
};

struct unique_lines {
    struct line *lines;  // the first copy of each line, in file order, or NULL
    size_t len;          // the number of lines
    char *data;          // the bytes of the file, which the lines point into
};

// remove_duplicate_lines reads the file at path, splits it into lines at each
// LF, and keeps the first copy of each line, in the order of the file. A last
// line with no LF is a line too. It fills *out and returns 0. Free the result
// with unique_lines_free. On an error it returns -1 and sets errno: the error
// of fopen, EIO for a read error, or ENOMEM.
int remove_duplicate_lines(const char *path, struct unique_lines *out);

// unique_lines_free frees the memory of a result of remove_duplicate_lines.
void unique_lines_free(struct unique_lines *u);

#endif
test_remove_duplicate_lines.c 90 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-duplicate-lines/.

#include "remove_duplicate_lines.h"

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

static const char *path = "remove_duplicate_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 *const *want, size_t n) {
    write_file(data, size);
    struct unique_lines got;
    if (remove_duplicate_lines(path, &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);
        }
    }
    unique_lines_free(&got);
}

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

int main(void) {
    CASE("simple", "b\na\nb\nc\na\n", "b", "a", "c");
    CASE("adjacent", "a\na\nb\n", "a", "b");
    CASE("no-duplicates", "c\nb\na\n", "c", "b", "a");
    check("empty", "", 0, NULL, 0);
    CASE("empty-lines", "\na\n\n\n", "", "a");
    CASE("all-same", "x\nx\nx\n", "x");
    CASE("no-final-newline", "a\nb\na", "a", "b");
    CASE("crlf", "a\r\na\n", "a\r", "a");
    CASE("case", "A\na\nA\n", "A", "a");
    CASE("whitespace", "a \na\n a\na \n", "a ", "a", " a");
    // U+00E9 is C3 A9. e and U+0301 is 65 CC 81.
    CASE("normalization", "\xc3\xa9\ne\xcc\x81\n\xc3\xa9\n", "\xc3\xa9", "e\xcc\x81");

    // 100000 lines with 1000 different lines make the table grow more than once.
    char *data = malloc(100000 * 4);
    assert(data != NULL);
    size_t size = 0;
    for (int i = 0; i < 100000; i++) {
        size += (size_t)snprintf(data + size, 100000 * 4 - size, "%d\n", i % 1000);
    }
    write_file(data, size);
    free(data);
    struct unique_lines got;
    assert(remove_duplicate_lines(path, &got) == 0);
    assert(got.len == 1000);
    for (size_t i = 0; i < got.len; i++) {
        char want[24];
        snprintf(want, sizeof want, "%zu", i);
        assert(strcmp(got.lines[i].text, want) == 0);
    }
    unique_lines_free(&got);

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

using System.Text;

/// <summary>Removes the duplicate lines of a text file.</summary>
public static class UniqueLines
{
    /// <summary>
    /// Returns the lines of the UTF-8 file at path, with only the first copy of each line, in the
    /// order of the file. 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>
    public static List<string> Read(string path)
    {
        byte[] data = File.ReadAllBytes(path);
        var seen = new HashSet<string>(StringComparer.Ordinal);
        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);
            // Add returns false if the set has the line already.
            if (seen.Add(line))
            {
                lines.Add(line);
            }
            start = end + 1;
        }
        return lines;
    }
}
UniqueLinesTests.cs 53 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-duplicate-lines/.

using System.Text;
using Xunit;

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

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

    // 100000 lines with 1000 different lines.
    private static string ManyLines() =>
        string.Concat(Enumerable.Range(0, 100000).Select(i => $"{i % 1000}\n"));

    private static string[] Numbers(int n) =>
        [.. Enumerable.Range(0, n).Select(i => i.ToString())];

    public static TheoryData<string, string, string[]> Cases => new()
    {
        { "simple", "b\na\nb\nc\na\n", ["b", "a", "c"] },
        { "adjacent", "a\na\nb\n", ["a", "b"] },
        { "no-duplicates", "c\nb\na\n", ["c", "b", "a"] },
        { "empty", "", [] },
        { "empty-lines", "\na\n\n\n", ["", "a"] },
        { "all-same", "x\nx\nx\n", ["x"] },
        { "no-final-newline", "a\nb\na", ["a", "b"] },
        { "crlf", "a\r\na\n", ["a\r", "a"] },
        { "case", "A\na\nA\n", ["A", "a"] },
        { "whitespace", "a \na\n a\na \n", ["a ", "a", " a"] },
        // U+00E9 and e with U+0301 look the same, but their code points are not equal.
        { "normalization", "\u00e9\ne\u0301\n\u00e9\n", ["\u00e9", "e\u0301"] },
        { "many-lines", ManyLines(), Numbers(1000) },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void Read(string name, string text, 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, UniqueLines.Read(path));
        _ = name;
    }

    [Fact]
    public void NotFound()
    {
        Assert.Throws<FileNotFoundException>(() => UniqueLines.Read(Path.Combine(dir, "missing.txt")));
    }
}
removeDuplicateLines.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-duplicate-lines/.

import { readFileSync } from "node:fs";

// Returns the lines of the UTF-8 file at path, each one only once, at the
// place of its first copy. 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".
export function removeDuplicateLines(path) {
  // readline also ends a line at a CR, so the code splits the bytes itself.
  const data = readFileSync(path);
  // A Set keeps its values in the order in which they were first added.
  const unique = new Set();
  let start = 0;
  while (start < data.length) {
    let end = data.indexOf(0x0a, start);
    if (end === -1) end = data.length;
    unique.add(data.toString("utf8", start, end));
    start = end + 1;
  }
  return [...unique];
}
removeDuplicateLines.test.js 45 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-duplicate-lines/.

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 { removeDuplicateLines } from "./removeDuplicateLines.js";

const numbers = (n) => Array.from({ length: n }, (_, i) => String(i));

// name: [the text of the file, written as UTF-8, the result]
const CASES = {
  simple: ["b\na\nb\nc\na\n", ["b", "a", "c"]],
  adjacent: ["a\na\nb\n", ["a", "b"]],
  "no-duplicates": ["c\nb\na\n", ["c", "b", "a"]],
  empty: ["", []],
  "empty-lines": ["\na\n\n\n", ["", "a"]],
  "all-same": ["x\nx\nx\n", ["x"]],
  "no-final-newline": ["a\nb\na", ["a", "b"]],
  crlf: ["a\r\na\n", ["a\r", "a"]],
  case: ["A\na\nA\n", ["A", "a"]],
  whitespace: ["a \na\n a\na \n", ["a ", "a", " a"]],
  // U+00E9, then e and U+0301: the same letter, but not the same code points.
  normalization: ["\u00e9\ne\u0301\n\u00e9\n", ["\u00e9", "e\u0301"]],
  // 100000 lines with 1000 different lines.
  "many-lines": [Array.from({ length: 100000 }, (_, i) => `${i % 1000}\n`).join(""), numbers(1000)],
};

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

for (const [name, [text, expect]] of Object.entries(CASES)) {
  test(name, () => {
    const path = join(dir, `${name}.txt`);
    writeFileSync(path, text, "utf8");
    assert.deepEqual(removeDuplicateLines(path), expect);
  });
}

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

import { readFileSync } from "node:fs";

// Returns the lines of the UTF-8 file at path, each one only once, at the
// place of its first copy. 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".
export function removeDuplicateLines(path: string): string[] {
  // readline also ends a line at a CR, so the code splits the bytes itself.
  const data = readFileSync(path);
  // A Set keeps its values in the order in which they were first added.
  const unique = new Set<string>();
  let start = 0;
  while (start < data.length) {
    let end = data.indexOf(0x0a, start);
    if (end === -1) end = data.length;
    unique.add(data.toString("utf8", start, end));
    start = end + 1;
  }
  return [...unique];
}
removeDuplicateLines.test.ts 45 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-duplicate-lines/.

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 { removeDuplicateLines } from "./removeDuplicateLines.ts";

const numbers = (n: number): string[] => Array.from({ length: n }, (_, i) => String(i));

// name: [the text of the file, written as UTF-8, the result]
const CASES: Record<string, [string, string[]]> = {
  simple: ["b\na\nb\nc\na\n", ["b", "a", "c"]],
  adjacent: ["a\na\nb\n", ["a", "b"]],
  "no-duplicates": ["c\nb\na\n", ["c", "b", "a"]],
  empty: ["", []],
  "empty-lines": ["\na\n\n\n", ["", "a"]],
  "all-same": ["x\nx\nx\n", ["x"]],
  "no-final-newline": ["a\nb\na", ["a", "b"]],
  crlf: ["a\r\na\n", ["a\r", "a"]],
  case: ["A\na\nA\n", ["A", "a"]],
  whitespace: ["a \na\n a\na \n", ["a ", "a", " a"]],
  // U+00E9, then e and U+0301: the same letter, but not the same code points.
  normalization: ["\u00e9\ne\u0301\n\u00e9\n", ["\u00e9", "e\u0301"]],
  // 100000 lines with 1000 different lines.
  "many-lines": [Array.from({ length: 100000 }, (_, i) => `${i % 1000}\n`).join(""), numbers(1000)],
};

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

for (const [name, [text, expect]] of Object.entries(CASES)) {
  test(name, () => {
    const path = join(dir, `${name}.txt`);
    writeFileSync(path, text, "utf8");
    assert.deepEqual(removeDuplicateLines(path), expect);
  });
}

test("not-found", () => {
  assert.throws(() => removeDuplicateLines(join(dir, "missing.txt")), { code: "ENOENT" });
});
remove_duplicate_lines.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-duplicate-lines/.

// Package dedup removes the duplicate lines of a text file.
package dedup

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

// RemoveDuplicateLines returns the lines of the UTF-8 file at path, each one
// only once, at the place of its first copy. A line ends at LF, and the LF is
// not part of it. A last line with no LF is a line too. Memory grows with the
// different lines, not with the size of the file. A missing file gives an
// error that matches fs.ErrNotExist.
func RemoveDuplicateLines(path string) ([]string, error) {
	f, err := os.Open(path)
	if err != nil {
		return nil, err
	}
	defer f.Close()
	r := bufio.NewReader(f)
	seen := map[string]bool{}
	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 !seen[line] {
				seen[line] = true
				lines = append(lines, line)
			}
		}
		if err != nil {
			return lines, nil
		}
	}
}
remove_duplicate_lines_test.go 76 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-duplicate-lines/.

package dedup

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

// manyLines returns 100000 lines with 1000 different lines, and the result.
func manyLines() (string, []string) {
	var b strings.Builder
	for i := range 100000 {
		b.WriteString(strconv.Itoa(i%1000) + "\n")
	}
	want := make([]string, 1000)
	for i := range want {
		want[i] = strconv.Itoa(i)
	}
	return b.String(), want
}

var manyData, manyWant = manyLines()

var cases = []struct {
	name string
	data string
	want []string
}{
	{"simple", "b\na\nb\nc\na\n", []string{"b", "a", "c"}},
	{"adjacent", "a\na\nb\n", []string{"a", "b"}},
	{"no-duplicates", "c\nb\na\n", []string{"c", "b", "a"}},
	{"empty", "", []string{}},
	{"empty-lines", "\na\n\n\n", []string{"", "a"}},
	{"all-same", "x\nx\nx\n", []string{"x"}},
	{"no-final-newline", "a\nb\na", []string{"a", "b"}},
	{"crlf", "a\r\na\n", []string{"a\r", "a"}},
	{"case", "A\na\nA\n", []string{"A", "a"}},
	{"whitespace", "a \na\n a\na \n", []string{"a ", "a", " a"}},
	// U+00E9, then e and U+0301: the same letter, but not the same code points.
	{"normalization", "\u00e9\ne\u0301\n\u00e9\n", []string{"\u00e9", "e\u0301"}},
	{"many-lines", manyData, manyWant},
}

func TestRemoveDuplicateLines(t *testing.T) {
	dir := t.TempDir()
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			path := filepath.Join(dir, c.name+".txt")
			if err := os.WriteFile(path, []byte(c.data), 0o644); err != nil {
				t.Fatal(err)
			}
			got, err := RemoveDuplicateLines(path)
			if err != nil {
				t.Fatal(err)
			}
			if !slices.Equal(got, c.want) {
				t.Errorf("got %q, want %q", got, c.want)
			}
		})
	}
}

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

//! Removes the duplicate lines of a text file.

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

/// Returns the lines of the UTF-8 file at `path`, each one only once, at the
/// place of its first copy. A line ends at LF, and the LF is not part of it. A
/// last line with no LF is a line too. Memory grows with the different lines,
/// not with the size of the file. A missing file gives an error of the kind
/// `ErrorKind::NotFound`, and a file that is not valid UTF-8 gives
/// `ErrorKind::InvalidData`.
pub fn remove_duplicate_lines(path: impl AsRef<Path>) -> io::Result<Vec<String>> {
    let mut reader = BufReader::new(File::open(path)?);
    let mut seen: HashSet<String> = HashSet::new();
    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();
        }
        // contains takes a &str, so a duplicate line needs no copy. A new
        // line is copied once into the set and moved into the result.
        if !seen.contains(line.as_str()) {
            seen.insert(line.clone());
            lines.push(std::mem::take(&mut line));
        }
        line.clear();
    }
    Ok(lines)
}
tests/remove_duplicate_lines_test.rs 55 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-duplicate-lines/.

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

use algo_remove_duplicate_lines::remove_duplicate_lines;

/// Writes the text to a new file in the temporary directory and returns its path.
fn write(name: &str, text: &str) -> PathBuf {
    let dir = std::env::temp_dir().join(format!("remove-duplicate-lines-{}", std::process::id()));
    fs::create_dir_all(&dir).unwrap();
    let path = dir.join(name);
    fs::write(&path, text).unwrap();
    path
}

const CASES: &[(&str, &str, &[&str])] = &[
    ("simple", "b\na\nb\nc\na\n", &["b", "a", "c"]),
    ("adjacent", "a\na\nb\n", &["a", "b"]),
    ("no-duplicates", "c\nb\na\n", &["c", "b", "a"]),
    ("empty", "", &[]),
    ("empty-lines", "\na\n\n\n", &["", "a"]),
    ("all-same", "x\nx\nx\n", &["x"]),
    ("no-final-newline", "a\nb\na", &["a", "b"]),
    ("crlf", "a\r\na\n", &["a\r", "a"]),
    ("case", "A\na\nA\n", &["A", "a"]),
    ("whitespace", "a \na\n a\na \n", &["a ", "a", " a"]),
    // U+00E9, then e and U+0301: the same letter, but not the same code points.
    ("normalization", "\u{e9}\ne\u{301}\n\u{e9}\n", &["\u{e9}", "e\u{301}"]),
];

#[test]
fn cases() {
    for &(name, text, want) in CASES {
        let path = write(&format!("{name}.txt"), text);
        assert_eq!(remove_duplicate_lines(&path).unwrap(), want, "{name}");
    }
}

#[test]
fn many_lines() {
    // 100000 lines with 1000 different lines.
    let text: String = (0..100000).map(|i| format!("{}\n", i % 1000)).collect();
    let want: Vec<String> = (0..1000).map(|i| i.to_string()).collect();
    let path = write("many-lines.txt", &text);
    assert_eq!(remove_duplicate_lines(&path).unwrap(), want);
}

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

# remove_duplicate_lines PATH
# Prints the lines of the file at PATH, with only the first copy of each line,
# in the order of the file, each with an LF at the end. Returns a nonzero
# status, and prints nothing on stdout, if the file cannot be read.
remove_duplicate_lines() {
  [[ -r $1 && ! -d $1 ]] || { printf 'remove_duplicate_lines: cannot read %s\n' "$1" >&2; return 1; }
  # seen[$0] is 0 the first time that awk sees a line, so !seen[$0]++ is true
  # and awk prints the line. The ++ makes it 1, so the next copies are not
  # printed. LC_ALL=C makes awk compare the bytes of the lines.
  LC_ALL=C awk '!seen[$0]++' "$1"
}
test_remove_duplicate_lines.bats 40 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/remove-duplicate-lines/.

bats_require_minimum_version 1.5.0

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

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

@test "simple" { check 'b\na\nb\nc\na\n' 'b\na\nc\n'; }
@test "adjacent" { check 'a\na\nb\n' 'a\nb\n'; }
@test "no-duplicates" { check 'c\nb\na\n' 'c\nb\na\n'; }
@test "empty" { check '' ''; }
@test "empty-lines" { check '\na\n\n\n' '\na\n'; }
@test "all-same" { check 'x\nx\nx\n' 'x\n'; }
@test "no-final-newline" { check 'a\nb\na' 'a\nb\n'; }
@test "crlf" { check 'a\r\na\n' 'a\r\na\n'; }
@test "case" { check 'A\na\nA\n' 'A\na\n'; }
@test "whitespace" { check 'a \na\n a\na \n' 'a \na\n a\n'; }
@test "normalization" { check '\xc3\xa9\ne\xcc\x81\n\xc3\xa9\n' '\xc3\xa9\ne\xcc\x81\n'; }

@test "many-lines" {
  seq 0 99999 | awk '{ print $1 % 1000 }' >"$file"
  [ "$(remove_duplicate_lines "$file")" = "$(seq 0 999)" ]
}

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

References

  1. The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), uniq, DESCRIPTION
  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, io, IOBase.readline; TextIOWrapper (newline)
  4. The Python Standard Library, Built-in Types, Mapping types, dict (fromkeys)
  5. MDN Web Docs, Set, Description
  6. Java SE 25 API, java.util.LinkedHashSet
  7. .NET API reference, HashSet<T>.Add, Returns
  8. Go standard library, package bufio, Reader.ReadString; Reader.ReadBytes
  9. The Rust Standard Library, std::io::BufRead, read_line; read_until
  10. The Rust Standard Library, std::collections::HashSet, insert
  11. cppreference.com, std::getline
  12. cppreference.com, std::unordered_set::insert, Return value
  13. The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), awk, DESCRIPTION; Expressions in awk; Variables and Special Variables
  14. The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), sort, OPTIONS (-u)
  15. MDN Web Docs, String.prototype.normalize(), 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