Taskcore
Replace text in many files
Also called globally replace text in several files, search and replace in many files, find and replace in files, sed s/old/new/g on many files.
Replace each instance of a text with another text in a list of files, and write each changed file to a new file that a rename puts in the place of the old one.
- Evidence
- Code in 10 languages
Task
Replace a text with another text in a list of files. Rosetta Code states the task like this: "Replace every occurring instance of a piece of text in a group of text files with another one."1 In its example, the old text is Goodbye London! and the new text is Hello New York!. The function on this page takes the list of files, the old text and the new text. It returns the number of instances that it replaced in each file.
The task needs rules for what an instance is and for what to do with each file. This page uses these rules:
- The old text and the new text are plain text, not patterns. A
.in the old text matches only a., and a$or a&in the new text goes into the file as it is. The search is case-sensitive. - The code compares bytes. The old text and the new text are UTF-8 text, and the code compares the bytes of the old text with the bytes of the file. The code does not decode the file, so the bytes that it does not replace do not change. An instance can contain LF bytes, so the old text can go across lines. CRLF is two bytes like the others.
- Instances do not overlap. The search starts at the start of the file and finds the first instance. It then goes on after the end of that instance. So in
aaa, the old textaahas one instance, and the file becomesbaif the new text isb. The code does not search the new text, so a new text that contains the old text does not cause a loop. - A file with no instance is not written. Its bytes, its modification time and its permissions do not change.
- A changed file is replaced in one step. The code writes the new text to a new file in the same directory, gives it the permissions of the old file, and renames it to the name of the old file.
- An empty old text is an error. An empty text has no clear instances, and the function checks it before it opens a file.
- The files are done in order, and the first error stops the function. If a file does not exist or cannot be written, the function reports the error. The files before it have the new text, and the files after it do not change.
Solutions
The method is the same in each language:
- Check that the old text is not empty.
- For each file, read the file as bytes. Find each instance from the left, and copy the bytes between the instances and the new text to a buffer. Count the instances.
- If the count is 0, go on to the next file.
- Otherwise, write the buffer to a new file in the same directory, give it the permissions of the old file, write its data to the disk, and rename it to the name of the old file.
The rename is the step that changes the file. POSIX says that during a rename, a directory entry named new "shall remain visible to other threads throughout the renaming operation and refer either to the file referred to by new or old before the operation began."2 So a program that opens the file gets the old text or the new text, and never a part of a file. If the function stops before the rename, the old file does not change.
All the solutions except Bash read the whole file into memory. The Bash solution reads the file one line at a time.
- Python. The file opens in binary mode.
bytes.countgives the count: "Return the number of non-overlapping occurrences of subsequence sub in the range [ start , end ]."3 Thenbytes.replacemakes the new bytes: "Return a copy of the sequence with all occurrences of subsequence old replaced by new ."3 Both find the instances from the left, so the count agrees with the replacement.tempfile.mkstempmakes the new file,shutil.copymodecopies the permissions,os.fsyncwrites the data to the disk, andos.replacerenames the file. If the new name exists, the file "will be replaced silently if the user has permission."4 An empty old text raisesValueError. - JavaScript and TypeScript (Node.js).
readFileSyncgives aBuffer, andindexOf(oldBytes, from)returns "The index of the first occurrence of value in buf , or -1 if buf does not contain value".5 The loop keeps the parts of the buffer and the new bytes in an array, andBuffer.concatjoins them. The new file opens with the flag'wx', which is "Like 'w' but fails if the path exists".6fsyncSyncwrites the data to the disk,chmodSynccopies the permissions, andrenameSyncrenames the file. An empty old text throws aRangeError. The TypeScript file adds types only. - Java.
Files.readAllBytesreads the file, and a loop compares the bytes of the old text with the bytes at each position.Files.createTempFile(dir, prefix, suffix)"Creates a new empty file in the specified directory, using the given prefix and suffix strings to generate its name."7 AFileOutputStreamwrites the bytes, andgetFD().sync()writes them to the disk. If the file system has POSIX permissions,setPosixFilePermissionscopies them.Files.movewithATOMIC_MOVErenames the file. An empty old text throws anIllegalArgumentException. - C#.
File.ReadAllBytesreads the file.data.AsSpan(from).IndexOf(oldBytes)"Searches for the specified sequence and returns the index of its first occurrence."8 AFileStreamwithFileMode.CreateNewmakes the new file, andFlush(true)writes the data to the disk. On Unix,File.SetUnixFileModecopies the permissions.File.Move(tmp, path, overwrite: true)renames the file, with the parameter overwrite set to true, "which replaces the file if it exists".9 An empty old text throws anArgumentException. - Go.
os.ReadFilereads the file.bytes.Count"counts the number of non-overlapping instances of sep in s".10bytes.ReplaceAll"returns a copy of the slice s with all non-overlapping instances of old replaced by new."10os.CreateTempmakes the new file,Chmodcopies the permissions, andSync"commits the current contents of the file to stable storage."11os.Renamerenames the file: "If newpath already exists and is not a directory, Rename replaces it."11 A deferred function removes the new file if a step fails. An empty old text givesErrEmptyOld. - Rust.
fs::readreads the file.windows(old.len()).position(...)finds the next instance, and the code copies the bytes before it and the new bytes to aVec<u8>. The new file opens withcreate_new, so the code does not write over a file that has the same name.set_permissionscopies the permissions,sync_allwrites the data to the disk, andfs::renamerenames the file, "replacing the original file if to already exists".12 An empty old text gives an error of kindInvalidInput. - C.
read_filereads the file into a buffer thatreallocmakes larger. A loop withmemcmpfinds each instance.mkstempmakes the new file from the path and the suffix.XXXXXX,fchmodcopies the permissions,fsyncwrites the data to the disk, andrenamerenames the file.replace_in_filesputs the counts in an array that the caller gives, and returns 0, or -1 witherrnoset. An empty old text setserrnotoEINVAL. - C++. A binary
std::ifstreamreads the file into astd::string.std::string::find(old_text, from)"Finds the first substring equal to the given character sequence. Search begins at pos".13 The new file has a random suffix and opens withstd::ios::noreplace(C++23).fs::permissionscopies the permissions, andfs::renamerenames the file. This solution uses only the standard library, so it does not write the data to the disk before the rename. The result is astd::expected<std::vector<std::size_t>, ReplaceError>. - Bash.
replace_in_files OLD NEW FILE...prints one count on each line. Anawkprogram reads the file one line at a time and keeps the text that it did not write in a variable.indexfinds plain text: it returns "the position, in characters, numbering from 1, in string s where string t first occurs, or zero if it does not occur at all."14 The program writes the text before each instance and the new text, and keeps only the last bytes, fewer than the length of the old text, because an instance can start there and go on in the next line.LC_ALL=Cmakesawkcount bytes. The texts go toawkin environment variables andENVIRON, not with-v(see the pitfalls).awkdoes not tell if the last line ends with LF, so the function looks at the last byte withtail -c 1.mktempmakes the new file from the template$file.XXXXXX,cp -pgives it the permissions of the old file, andmv -frenames it. On an error, the function returns 2 with a message. It does not write the data to the disk before the rename, and it does not support a NUL byte in a file.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl. For each case, the directory fixtures/NAME holds the files before the call, and fixtures/NAME.after holds the files after the call.
rosetta:Goodbye London!becomesHello New York!in two files. The second file has two instances, and a line withGoodbyeonly, which does not change. The result is 1 and 2.some-files-match:dogbecomesfox. The first file has nodog, so it is not written. The result is 0 and 2.one-file:1becomes2in a file with two lines. The result is 2.no-files: an empty list. The result is an empty list.no-matchandempty-file: no instance. The result is 0, and the file does not change.deleteandwhole-file: the new text is empty.-goes froma-b-c, andabcgoes from a file that holds onlyabc, which is then empty.new-contains-old:abecomesaaina a. The result is 2, and the file isaa aa.overlappingandadjacent:aabecomesb.aaahas one instance and becomesba.aaaahas two instances and becomesbb.special-chars:1.5becomes the text\&$1 $& [x], with each character as it is.125does not change, because.is not a pattern.glob-chars:*.txtbecomes?. Only the text*.txtchanges, anda.txtstays.across-lines:end, LF,startbecomesend start. The old text goes across two lines.lf-to-crlf: LF becomes CRLF. The result is 2.crlf:abecomescin a file with CRLF line ends. The CR bytes do not change.no-final-newline: the file has no LF at the end, and does not get one.non-ascii:ébecomeseincafé, cafe. The old text is two bytes in UTF-8.case-sensitive:hellobecomesbyeinHello hello.Hellodoes not change.
The tests also write a file of 100000 lines, each line line and a number, and replace line with L. The result is 100000. Other tests check that a file with mode 640 keeps its mode, that no new file stays in the directory, and that a file with no instance is not written. The cases in cases/errors.jsonl must give the error not-found or bad-old. In the case stop, the second file of three does not exist: the first file has the new text, and the third file does not change. The toolchain does not load cases/errors.jsonl yet, so each test file holds these cases by name.
Pitfalls
- In
sed, the old text is a regular expression and&in the new text is the match. POSIX says that an&"appearing in the replacement shall be replaced by the string matching the RE."15 Sos/1.5/[&]/galso changes125, and the new text is the match in brackets. To usesedfor plain text, put a backslash before each special character of the old text and before each&,\and delimiter of the new text:
# Wrong: in sed, . matches any character and & is the text that matched.
printf '1.5 and 125\n' | sed 's/1.5/[&]/g'
# Right: a backslash before . and & makes each one a plain character.
printf '1.5 and 125\n' | sed 's/1\.5/[\&]/g'
[1.5] and [125]
[&] and 125
- In JavaScript,
$patterns in the new text have a meaning. Forreplace, "The replacement string can include the following special replacement patterns".16$&"Inserts the matched substring.",16 and$$inserts one$.replaceAllis the same: "The replacement has the same semantics as that of String.prototype.replace() ."17 A function as the replacement does not have this problem, because the code uses its result as it is:
const text = 'echo PID';
const newText = '$$';
// Wrong: in the replacement string, $$ inserts one $.
console.log(text.replaceAll('PID', newText));
// Right: replaceAll uses the result of a function as it is.
console.log(text.replaceAll('PID', () => newText));
echo $
echo $$
- In Python,
re.subchanges backslashes in the new text. If the replacement is a string, "any backslash escapes in it are processed. That is, \n is converted to a single newline character, \r is converted to a carriage return, and so forth."18 So a Windows path such asC:\newgets an LF. Usestr.replaceorbytes.replacefor plain text, or givere.suba function:
import re
text = 'path = DIR\n'
new = r'C:\new'
# Wrong: re.sub changes the two characters \n in new to an LF.
print(re.sub('DIR', new, text), end='')
# Right: str.replace uses new as it is.
print(text.replace('DIR', new), end='')
# Also right: re.sub uses the result of a function as it is.
print(re.sub('DIR', lambda match: new, text), end='')
path = C:
ew
path = C:\new
path = C:\new
- In Bash,
&in the new text can be the match. In Bash 5.2 and later, withpatsub_replacement, an unquoted&in the replacement of${text//old/new}is the text that matched. The manual says about the option: "This option is enabled by default."19 It also says: "Quoting any part of string inhibits replacement in the expansion of the quoted portion, including replacement strings stored in shell variables."19 So write${text//"$old"/"$new"}with quotes. This expansion is also slow on a large text. In a test on macOS with Bash 3.2, two expansions of this type took 9.5 seconds for a text of 2000 short lines, and 73 seconds for 4000 lines. This is why the Bash solution usesawk. awk -vchanges backslashes. For an assignment, POSIX says that the characters after the="shall be interpreted as if they appeared in the awk program preceded and followed by a double-quote".14 So with-v new='C:\new', the variable holds an LF. The Bash solution puts the texts in environment variables, and reads them fromENVIRON, which gives them as they are.xargssplits file names at blanks. If no-0option is given,xargssplits its input at blanks and newlines, and it gives quotes a meaning.20 Sofind . -name '*.txt' | xargs sed ...breaks a file namedmy notes.txtinto two names. Usefind ... -exec cmd {} +, for which "the pathnames for which the primary is evaluated shall be aggregated into sets",21 or usefind ... -print0 | xargs -0. The option-0makesxargs"Use a null byte as the input argument delimiter and do not treat any other input bytes as special."20- A count that steps by one byte counts overlapping instances. A loop that finds an instance and then searches again from the next byte counts two instances of
aainaaa, but the replacement changes only one. Continue the search after the end of the instance, asbytes.Countin Go does: it "counts the number of non-overlapping instances of sep in s."10 - An empty old text gives strange results. In Go, "If sep is an empty slice, Count returns 1 + the number of UTF-8-encoded code points in s."10 A replacement with an empty old text puts the new text between each pair of characters. The solutions here check the old text first and report an error.
- The rename replaces a symbolic link, not its target. POSIX says: "If either the old or new argument names a symbolic link, rename () shall operate on the symbolic link itself, and shall not resolve the last component of the argument."2 If a path in the list is a symbolic link, the solutions read the target, but after the rename the path is a regular file with the new text, and the target does not change. To change the target, resolve the path first, for example with
os.path.realpathin Python. - The new file must be on the same file system. A temp directory such as
/tmpcan be on a different file system from the old file. Rust says aboutfs::rename: "This will not work if the new name is on a different mount point."12 Make the new file in the directory of the old file, as all the solutions here do. - An atomic move can fail if the target exists. For
ATOMIC_MOVE, Java says: "If the target file exists then it is implementation specific if the existing file is replaced or this method fails by throwing an IOException".7 On such a system, the Java solution throws the exception, deletes the new file and does not change the old file. - Writing each file changes files that have no instance. If the code writes each file in the list, a file with no instance gets a new modification time, and a program that looks at the times sees a change that is not there. The solutions here write a file only if its count is more than 0.
Related tasks
- Write a file atomically: write a new file and rename it over the old one, the method that this page uses.
- Rename a file: rename a file, and what happens if the new name exists.
- Replace a substring: replace a text with another text in a string in memory.
- Remove lines from a file: remove a range of lines from a file with the same write and rename steps.
- Filter lines that match a pattern: keep the lines in which a regular expression matches.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/replace-text-in-many-files/.
"""Replaces a text with another text in each file of a list."""
import os
import shutil
import tempfile
from collections.abc import Iterable
from os import PathLike
def replace_in_files(paths: Iterable[str | PathLike[str]], old: str, new: str) -> list[int]:
"""Replaces each instance of old with new in each file, and returns the number of instances in each file.
old and new are plain text, not patterns. The function compares the UTF-8
bytes of old with the bytes of each file, so it does not decode the file,
and an instance can contain LF bytes. Instances do not overlap. A file with
no instance is not written. A changed file goes to a new file in the same
directory, and os.replace puts the new file in the place of the old one.
The files are done in order. At the first error, the function stops: the
files before have the new text, and the files after do not change. Raises
ValueError if old is empty, and FileNotFoundError if a file does not exist.
"""
if not old:
raise ValueError("old is empty")
old_bytes, new_bytes = old.encode(), new.encode()
counts = []
for path in paths:
with open(path, "rb") as f:
data = f.read()
# bytes.count and bytes.replace both find instances that do not overlap,
# from left to right, so the count is the number of replacements.
n = data.count(old_bytes)
if n > 0:
write_atomically(path, data.replace(old_bytes, new_bytes))
counts.append(n)
return counts
def write_atomically(path: str | PathLike[str], data: bytes) -> None:
"""Writes data to a new file next to path, and renames it over path."""
directory, name = os.path.split(os.fspath(path))
fd, tmp = tempfile.mkstemp(prefix=f".{name}.", suffix=".tmp", dir=directory or ".")
try:
with os.fdopen(fd, "wb") as f:
f.write(data)
f.flush()
os.fsync(f.fileno())
# mkstemp makes the file readable and writable only by its owner.
shutil.copymode(path, tmp)
os.replace(tmp, path)
except BaseException:
if os.path.exists(tmp):
os.remove(tmp)
raise
test_replace_in_files.py 90 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/replace-text-in-many-files/.
import json
import os
import shutil
import stat
import tempfile
import unittest
from pathlib import Path
from replace_in_files import replace_in_files
NODE = Path(__file__).resolve().parents[2]
def load(name):
with open(NODE / "cases" / name, encoding="utf-8") as f:
return [json.loads(line) for line in f if line.strip()]
class ReplaceInFilesTest(unittest.TestCase):
def setUp(self):
self.dir = Path(tempfile.mkdtemp())
self.addCleanup(shutil.rmtree, self.dir)
def copy_case(self, name):
src = NODE / "fixtures" / name
dst = self.dir / name
if src.is_dir():
shutil.copytree(src, dst)
else:
dst.mkdir()
return dst
def test_cases(self):
for case in load("basic.jsonl") + load("edge.jsonl"):
with self.subTest(case["name"]):
name = case["name"]
work = self.copy_case(name)
args = case["args"]
paths = [work / Path(p).name for p in args["paths"]]
self.assertEqual(replace_in_files(paths, args["old"], args["new"]), case["expect"])
after = NODE / "fixtures" / (name + ".after")
for p in paths:
self.assertEqual(p.read_bytes(), (after / p.name).read_bytes())
self.assertEqual(sorted(os.listdir(work)), sorted(p.name for p in paths))
def test_many_lines(self):
path = self.dir / "many.txt"
path.write_text("".join(f"line {i}\n" for i in range(100000)))
self.assertEqual(replace_in_files([path], "line ", "L"), [100000])
self.assertEqual(path.read_text(), "".join(f"L{i}\n" for i in range(100000)))
def test_keeps_the_permissions(self):
path = self.dir / "a.txt"
path.write_text("a\n")
os.chmod(path, 0o640)
self.assertEqual(replace_in_files([path], "a", "b"), [1])
self.assertEqual(stat.S_IMODE(os.stat(path).st_mode), 0o640)
def test_no_match_does_not_write(self):
path = self.dir / "a.txt"
path.write_text("a\n")
before = os.stat(path).st_ino
self.assertEqual(replace_in_files([path], "x", "y"), [0])
self.assertEqual(os.stat(path).st_ino, before)
def test_errors(self):
cases = {c["name"]: c for c in load("errors.jsonl")}
self.assertEqual(set(cases), {"not-found", "empty-old", "stop"})
with self.assertRaises(FileNotFoundError):
replace_in_files([self.dir / "missing.txt"], "a", "b")
path = self.dir / "a.txt"
path.write_text("a\n")
with self.assertRaises(ValueError):
replace_in_files([path], "", "b")
self.assertEqual(path.read_text(), "a\n")
def test_stop(self):
work = self.copy_case("stop")
with self.assertRaises(FileNotFoundError):
replace_in_files([work / "a.txt", work / "missing.txt", work / "c.txt"], "a", "b")
after = NODE / "fixtures" / "stop.after"
for name in ("a.txt", "c.txt"):
self.assertEqual((work / name).read_bytes(), (after / name).read_bytes())
if __name__ == "__main__":
unittest.main()
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/replace-text-in-many-files/.
#include "replace_in_files.hpp"
#include <fstream>
#include <iterator>
#include <random>
#include <string>
#include <system_error>
namespace fs = std::filesystem;
namespace {
// Writes data to a new file next to path, and renames it over path.
bool write_atomically(const fs::path& path, const std::string& data) {
std::error_code ec;
const fs::perms perms = fs::status(path, ec).permissions();
if (ec) {
return false;
}
// The new file is next to path, with a random suffix. noreplace (C++23)
// makes the open fail if a file with that name exists.
std::random_device random;
fs::path tmp;
std::ofstream out;
for (int tries = 0; tries < 100 && !out.is_open(); tries++) {
tmp = path;
tmp += "." + std::to_string(random()) + ".tmp";
out.open(tmp, std::ios::binary | std::ios::out | std::ios::noreplace);
}
if (!out.is_open()) {
return false;
}
out.write(data.data(), static_cast<std::streamsize>(data.size()));
out.close();
if (out) {
fs::permissions(tmp, perms, ec);
if (!ec) {
fs::rename(tmp, path, ec);
if (!ec) {
return true;
}
}
}
fs::remove(tmp, ec);
return false;
}
} // namespace
std::expected<std::vector<std::size_t>, ReplaceError> replace_in_files(
const std::vector<fs::path>& paths, std::string_view old_text, std::string_view new_text) {
if (old_text.empty()) {
return std::unexpected(ReplaceError::empty_old);
}
std::vector<std::size_t> counts;
for (const fs::path& path : paths) {
// 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(ReplaceError::cannot_open);
}
const std::string data{std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>()};
if (in.bad()) {
return std::unexpected(ReplaceError::read_failed);
}
// find gives the first instance at or after from. The search goes on
// after the end of each instance.
std::string out;
std::size_t count = 0;
std::size_t from = 0;
for (std::size_t at; (at = data.find(old_text, from)) != std::string::npos;
from = at + old_text.size()) {
out.append(data, from, at - from);
out.append(new_text);
count++;
}
if (count > 0) {
out.append(data, from);
if (!write_atomically(path, out)) {
return std::unexpected(ReplaceError::write_failed);
}
}
counts.push_back(count);
}
return counts;
}
replace_in_files.hpp 23 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/replace-text-in-many-files/.
#pragma once
#include <cstddef>
#include <expected>
#include <filesystem>
#include <string_view>
#include <vector>
enum class ReplaceError { empty_old, cannot_open, read_failed, write_failed };
// Replaces each instance of old_text with new_text in each file, and returns
// the number of instances in each file. old_text and new_text are plain text,
// not patterns. Instances do not overlap. A file with no instance is not
// written. A changed file goes to a new file in the same directory, and
// std::filesystem::rename puts it in the place of the old one. The files are
// done in order, and the first error stops the function: the files before
// have the new text, and the files after do not change.
std::expected<std::vector<std::size_t>, ReplaceError> replace_in_files(
const std::vector<std::filesystem::path>& paths, std::string_view old_text,
std::string_view new_text);
test_replace_in_files.cpp 134 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/replace-text-in-many-files/.
#include "replace_in_files.hpp"
#include <fstream>
#include <iostream>
#include <iterator>
#include <random>
#include <string>
#include <vector>
namespace fs = std::filesystem;
namespace {
int failures = 0;
void check(bool ok, const std::string& name, const char* what) {
if (!ok) {
std::cerr << "FAIL " << name << ": " << what << '\n';
failures++;
}
}
void write_file(const fs::path& path, const std::string& text) {
std::ofstream(path, std::ios::binary) << text;
}
std::string read_file(const fs::path& path) {
std::ifstream in(path, std::ios::binary);
return {std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>()};
}
struct File {
std::string name, before, after;
};
struct Case {
std::string name, old_text, new_text;
std::vector<File> files;
std::vector<std::size_t> want;
};
std::string lines(const std::string& prefix) {
std::string s;
for (int i = 0; i < 100000; i++) {
s += prefix + std::to_string(i) + "\n";
}
return s;
}
} // namespace
int main() {
const std::vector<Case> cases = {
{"rosetta", "Goodbye London!", "Hello New York!",
{{"a.txt", "Goodbye London!\n", "Hello New York!\n"},
{"b.txt", "Goodbye London! Goodbye London!\nGoodbye\n", "Hello New York! Hello New York!\nGoodbye\n"}},
{1, 2}},
{"some-files-match", "dog", "fox", {{"a.txt", "cat\n", "cat\n"}, {"b.txt", "dog\ncat dog\n", "fox\ncat fox\n"}}, {0, 2}},
{"one-file", "1", "2", {{"a.txt", "x = 1\ny = 1\n", "x = 2\ny = 2\n"}}, {2}},
{"no-files", "a", "b", {}, {}},
{"no-match", "x", "y", {{"a.txt", "abc\n", "abc\n"}}, {0}},
{"empty-file", "a", "b", {{"a.txt", "", ""}}, {0}},
{"delete", "-", "", {{"a.txt", "a-b-c\n", "abc\n"}}, {2}},
{"whole-file", "abc", "", {{"a.txt", "abc", ""}}, {1}},
{"new-contains-old", "a", "aa", {{"a.txt", "a a\n", "aa aa\n"}}, {2}},
{"overlapping", "aa", "b", {{"a.txt", "aaa\n", "ba\n"}}, {1}},
{"adjacent", "aa", "b", {{"a.txt", "aaaa\n", "bb\n"}}, {2}},
{"special-chars", "1.5", "\\&$1 $& [x]", {{"a.txt", "1.5 and 125\n", "\\&$1 $& [x] and 125\n"}}, {1}},
{"glob-chars", "*.txt", "?", {{"a.txt", "a.txt *.txt\n", "a.txt ?\n"}}, {1}},
{"across-lines", "end\nstart", "end start", {{"a.txt", "end\nstart\n", "end start\n"}}, {1}},
{"lf-to-crlf", "\n", "\r\n", {{"a.txt", "a\nb\n", "a\r\nb\r\n"}}, {2}},
{"crlf", "a", "c", {{"a.txt", "a\r\nb\r\n", "c\r\nb\r\n"}}, {1}},
{"no-final-newline", "b", "c", {{"a.txt", "a b", "a c"}}, {1}},
{"non-ascii", "\xc3\xa9", "e", {{"a.txt", "caf\xc3\xa9" ", cafe\n", "cafe, cafe\n"}}, {1}},
{"case-sensitive", "hello", "bye", {{"a.txt", "Hello hello\n", "Hello bye\n"}}, {1}},
};
const fs::path root = fs::temp_directory_path() / ("replace-in-files-" + std::to_string(std::random_device{}()));
fs::create_directories(root);
int n = 0;
for (const Case& c : cases) {
const fs::path dir = root / std::to_string(n++);
fs::create_directory(dir);
std::vector<fs::path> paths;
for (const File& f : c.files) {
paths.push_back(dir / f.name);
write_file(paths.back(), f.before);
}
auto got = replace_in_files(paths, c.old_text, c.new_text);
check(got.has_value() && *got == c.want, c.name, "result");
for (const File& f : c.files) {
check(read_file(dir / f.name) == f.after, c.name, "after");
}
// No temporary file stays in the directory.
auto entries = std::distance(fs::directory_iterator(dir), fs::directory_iterator());
check(entries == static_cast<std::ptrdiff_t>(c.files.size()), c.name, "files");
}
const fs::path many = root / "many.txt";
write_file(many, lines("line "));
auto got = replace_in_files({many}, "line ", "L");
check(got.has_value() && *got == std::vector<std::size_t>{100000}, "many-lines", "result");
check(read_file(many) == lines("L"), "many-lines", "after");
const fs::path a = root / "a.txt";
write_file(a, "a\n");
fs::permissions(a, fs::perms::owner_read | fs::perms::owner_write | fs::perms::group_read);
got = replace_in_files({a}, "a", "b");
check(got.has_value() && (*got)[0] == 1, "keeps-the-permissions", "result");
check(fs::status(a).permissions() == (fs::perms::owner_read | fs::perms::owner_write | fs::perms::group_read),
"keeps-the-permissions", "mode");
got = replace_in_files({root / "missing.txt"}, "a", "b");
check(!got.has_value() && got.error() == ReplaceError::cannot_open, "not-found", "error");
got = replace_in_files({a}, "", "b");
check(!got.has_value() && got.error() == ReplaceError::empty_old, "empty-old", "error");
check(read_file(a) == "b\n", "empty-old", "after");
const fs::path stop = root / "stop";
fs::create_directory(stop);
write_file(stop / "a.txt", "a\n");
write_file(stop / "c.txt", "a\n");
got = replace_in_files({stop / "a.txt", stop / "missing.txt", stop / "c.txt"}, "a", "b");
check(!got.has_value() && got.error() == ReplaceError::cannot_open, "stop", "error");
check(read_file(stop / "a.txt") == "b\n" && read_file(stop / "c.txt") == "a\n", "stop", "after");
fs::remove_all(root);
if (failures == 0) {
std::cout << "ok\n";
}
return failures != 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/replace-text-in-many-files/.
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.PosixFileAttributeView;
import java.util.List;
/** Replaces a text with another text in each file of a list. */
public final class ReplaceInFiles {
private ReplaceInFiles() {}
/**
* Replaces each instance of oldText with newText in each file, and returns the number of
* instances in each file. oldText and newText are plain text, not patterns. The code compares
* the UTF-8 bytes of oldText with the bytes of each file, so an instance can contain LF bytes.
* Instances do not overlap. A file with no instance is not written. A changed file goes to a new
* file in the same directory, and an atomic move puts it in the place of the old one. The files
* are done in order, and the first error stops the method: the files before have the new text,
* and the files after do not change.
*
* @throws IllegalArgumentException if oldText is empty
* @throws java.nio.file.NoSuchFileException if a file does not exist
*/
public static int[] replace(List<Path> paths, String oldText, String newText) throws IOException {
if (oldText.isEmpty()) {
throw new IllegalArgumentException("oldText is empty");
}
byte[] oldBytes = oldText.getBytes(StandardCharsets.UTF_8);
byte[] newBytes = newText.getBytes(StandardCharsets.UTF_8);
int[] counts = new int[paths.size()];
for (int i = 0; i < counts.length; i++) {
Path path = paths.get(i);
byte[] data = Files.readAllBytes(path);
ByteArrayOutputStream out = new ByteArrayOutputStream(data.length);
int from = 0;
// The search goes on after the end of each instance.
for (int at; (at = indexOf(data, oldBytes, from)) != -1; from = at + oldBytes.length) {
out.write(data, from, at - from);
out.write(newBytes, 0, newBytes.length);
counts[i]++;
}
if (counts[i] > 0) {
out.write(data, from, data.length - from);
writeAtomically(path, out.toByteArray());
}
}
return counts;
}
/** Returns the index of the first instance of needle in data at or after from, or -1. */
private static int indexOf(byte[] data, byte[] needle, int from) {
outer:
for (int i = from; i <= data.length - needle.length; i++) {
for (int j = 0; j < needle.length; j++) {
if (data[i + j] != needle[j]) {
continue outer;
}
}
return i;
}
return -1;
}
/** Writes data to a new file next to path, and moves it over path. */
private static void writeAtomically(Path path, byte[] data) throws IOException {
Path dir = path.toAbsolutePath().getParent();
// createTempFile makes a file with a name that no file has.
Path tmp = Files.createTempFile(dir, "." + path.getFileName() + ".", ".tmp");
try {
try (FileOutputStream out = new FileOutputStream(tmp.toFile())) {
out.write(data);
out.getFD().sync();
}
if (Files.getFileAttributeView(path, PosixFileAttributeView.class) != null) {
Files.setPosixFilePermissions(tmp, Files.getPosixFilePermissions(path));
}
Files.move(tmp, path, StandardCopyOption.ATOMIC_MOVE);
} catch (IOException | RuntimeException e) {
Files.deleteIfExists(tmp);
throw e;
}
}
}
ReplaceInFilesTest.java 139 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/replace-text-in-many-files/.
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
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.nio.file.attribute.PosixFileAttributeView;
import java.nio.file.attribute.PosixFilePermissions;
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 ReplaceInFilesTest {
@TempDir Path dir;
/** One file: its name, the text before and the text after. */
record F(String name, String before, String after) {}
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("rosetta", "Goodbye London!", "Hello New York!",
List.of(new F("a.txt", "Goodbye London!\n", "Hello New York!\n"),
new F("b.txt", "Goodbye London! Goodbye London!\nGoodbye\n",
"Hello New York! Hello New York!\nGoodbye\n")),
new int[] {1, 2}),
Arguments.of("some-files-match", "dog", "fox",
List.of(new F("a.txt", "cat\n", "cat\n"), new F("b.txt", "dog\ncat dog\n", "fox\ncat fox\n")),
new int[] {0, 2}),
Arguments.of("one-file", "1", "2", List.of(new F("a.txt", "x = 1\ny = 1\n", "x = 2\ny = 2\n")), new int[] {2}),
Arguments.of("no-files", "a", "b", List.of(), new int[] {}),
Arguments.of("no-match", "x", "y", List.of(new F("a.txt", "abc\n", "abc\n")), new int[] {0}),
Arguments.of("empty-file", "a", "b", List.of(new F("a.txt", "", "")), new int[] {0}),
Arguments.of("delete", "-", "", List.of(new F("a.txt", "a-b-c\n", "abc\n")), new int[] {2}),
Arguments.of("whole-file", "abc", "", List.of(new F("a.txt", "abc", "")), new int[] {1}),
Arguments.of("new-contains-old", "a", "aa", List.of(new F("a.txt", "a a\n", "aa aa\n")), new int[] {2}),
Arguments.of("overlapping", "aa", "b", List.of(new F("a.txt", "aaa\n", "ba\n")), new int[] {1}),
Arguments.of("adjacent", "aa", "b", List.of(new F("a.txt", "aaaa\n", "bb\n")), new int[] {2}),
Arguments.of("special-chars", "1.5", "\\&$1 $& [x]",
List.of(new F("a.txt", "1.5 and 125\n", "\\&$1 $& [x] and 125\n")), new int[] {1}),
Arguments.of("glob-chars", "*.txt", "?", List.of(new F("a.txt", "a.txt *.txt\n", "a.txt ?\n")), new int[] {1}),
Arguments.of("across-lines", "end\nstart", "end start",
List.of(new F("a.txt", "end\nstart\n", "end start\n")), new int[] {1}),
Arguments.of("lf-to-crlf", "\n", "\r\n", List.of(new F("a.txt", "a\nb\n", "a\r\nb\r\n")), new int[] {2}),
Arguments.of("crlf", "a", "c", List.of(new F("a.txt", "a\r\nb\r\n", "c\r\nb\r\n")), new int[] {1}),
Arguments.of("no-final-newline", "b", "c", List.of(new F("a.txt", "a b", "a c")), new int[] {1}),
Arguments.of("non-ascii", "\u00e9", "e", List.of(new F("a.txt", "caf\u00e9, cafe\n", "cafe, cafe\n")), new int[] {1}),
Arguments.of("case-sensitive", "hello", "bye",
List.of(new F("a.txt", "Hello hello\n", "Hello bye\n")), new int[] {1}));
}
private static void write(Path path, String text) throws IOException {
Files.write(path, text.getBytes(StandardCharsets.UTF_8));
}
private static String read(Path path) throws IOException {
return new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void replace(String name, String oldText, String newText, List<F> files, int[] want)
throws IOException {
List<Path> paths = new ArrayList<>();
for (F f : files) {
paths.add(dir.resolve(f.name()));
write(paths.getLast(), f.before());
}
assertArrayEquals(want, ReplaceInFiles.replace(paths, oldText, newText));
for (F f : files) {
assertEquals(f.after(), read(dir.resolve(f.name())));
}
// No temporary file stays in the directory.
try (Stream<Path> s = Files.list(dir)) {
assertEquals(files.size(), s.count());
}
}
private static String lines(String prefix) {
StringBuilder b = new StringBuilder();
for (int i = 0; i < 100000; i++) {
b.append(prefix).append(i).append('\n');
}
return b.toString();
}
@Test
void manyLines() throws IOException {
Path path = dir.resolve("many.txt");
write(path, lines("line "));
assertArrayEquals(new int[] {100000}, ReplaceInFiles.replace(List.of(path), "line ", "L"));
assertEquals(lines("L"), read(path));
}
@Test
void keepsThePermissions() throws IOException {
assumeTrue(Files.getFileAttributeView(dir, PosixFileAttributeView.class) != null);
Path path = dir.resolve("a.txt");
write(path, "a\n");
Files.setPosixFilePermissions(path, PosixFilePermissions.fromString("rw-r-----"));
assertArrayEquals(new int[] {1}, ReplaceInFiles.replace(List.of(path), "a", "b"));
assertEquals("rw-r-----", PosixFilePermissions.toString(Files.getPosixFilePermissions(path)));
}
@Test
void notFound() {
assertThrows(NoSuchFileException.class,
() -> ReplaceInFiles.replace(List.of(dir.resolve("missing.txt")), "a", "b"));
}
@Test
void emptyOld() throws IOException {
Path path = dir.resolve("a.txt");
write(path, "a\n");
assertThrows(IllegalArgumentException.class, () -> ReplaceInFiles.replace(List.of(path), "", "b"));
assertEquals("a\n", read(path));
}
@Test
void stop() throws IOException {
write(dir.resolve("a.txt"), "a\n");
write(dir.resolve("c.txt"), "a\n");
List<Path> paths = List.of(dir.resolve("a.txt"), dir.resolve("missing.txt"), dir.resolve("c.txt"));
assertThrows(NoSuchFileException.class, () -> ReplaceInFiles.replace(paths, "a", "b"));
assertEquals("b\n", read(dir.resolve("a.txt")));
assertEquals("a\n", read(dir.resolve("c.txt")));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/replace-text-in-many-files/.
// mkstemp, fchmod and fsync are in POSIX, not in ISO C.
#define _POSIX_C_SOURCE 200809L
#include "replace_in_files.h"
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
// Reads the whole file at path into a new buffer that the caller frees.
static int read_file(const char *path, char **data, size_t *len) {
FILE *f = fopen(path, "rb");
if (f == NULL) {
return -1;
}
size_t cap = 4096, n = 0;
char *buf = malloc(cap);
while (buf != NULL) {
n += fread(buf + n, 1, cap - n, f);
if (n < cap) {
break;
}
char *bigger = realloc(buf, cap * 2);
if (bigger == NULL) {
free(buf);
buf = NULL;
break;
}
buf = bigger;
cap *= 2;
}
int e = errno;
if (buf == NULL || ferror(f)) {
free(buf);
fclose(f);
errno = buf == NULL ? ENOMEM : e;
return -1;
}
fclose(f);
*data = buf;
*len = n;
return 0;
}
// Returns a pointer to the first instance of the m bytes of needle in the n
// bytes of haystack, or NULL.
static const char *find(const char *haystack, size_t n, const char *needle, size_t m) {
for (size_t i = 0; m <= n && i <= n - m; i++) {
if (memcmp(haystack + i, needle, m) == 0) {
return haystack + i;
}
}
return NULL;
}
// Writes the len bytes of data to a new file next to path, and renames it over
// path.
static int write_atomically(const char *path, const char *data, size_t len) {
struct stat st;
if (stat(path, &st) != 0) {
return -1;
}
// mkstemp changes the six X characters to make a name that no file has.
// The name is path with a suffix, so it is in the same directory.
size_t plen = strlen(path);
char *tmp = malloc(plen + sizeof ".XXXXXX");
if (tmp == NULL) {
return -1;
}
memcpy(tmp, path, plen);
memcpy(tmp + plen, ".XXXXXX", sizeof ".XXXXXX");
int fd = mkstemp(tmp);
if (fd < 0) {
free(tmp);
return -1;
}
size_t done = 0;
while (done < len) {
ssize_t w = write(fd, data + done, len - done);
if (w < 0) {
goto fail;
}
done += (size_t)w;
}
// mkstemp makes the file readable and writable only by its owner.
if (fchmod(fd, st.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO)) != 0 || fsync(fd) != 0) {
goto fail;
}
int closed = close(fd);
fd = -1;
if (closed != 0 || rename(tmp, path) != 0) {
goto fail;
}
free(tmp);
return 0;
fail:;
int e = errno;
if (fd >= 0) {
close(fd);
}
unlink(tmp);
free(tmp);
errno = e;
return -1;
}
int replace_in_files(const char *const paths[], size_t n, const char *old_text, const char *new_text,
size_t counts[]) {
size_t old_len = strlen(old_text), new_len = strlen(new_text);
if (old_len == 0) {
errno = EINVAL;
return -1;
}
for (size_t i = 0; i < n; i++) {
char *data;
size_t len;
if (read_file(paths[i], &data, &len) != 0) {
return -1;
}
// First count the instances, to know the size of the new data. The
// search goes on after the end of each instance.
size_t count = 0;
const char *p = data, *end = data + len;
const char *at;
while ((at = find(p, (size_t)(end - p), old_text, old_len)) != NULL) {
count++;
p = at + old_len;
}
if (count > 0) {
size_t out_len = len - count * old_len + count * new_len;
char *out = malloc(out_len + 1);
if (out == NULL) {
free(data);
return -1;
}
char *q = out;
p = data;
while ((at = find(p, (size_t)(end - p), old_text, old_len)) != NULL) {
memcpy(q, p, (size_t)(at - p));
q += at - p;
memcpy(q, new_text, new_len);
q += new_len;
p = at + old_len;
}
memcpy(q, p, (size_t)(end - p));
int r = write_atomically(paths[i], out, out_len);
free(out);
if (r != 0) {
free(data);
return -1;
}
}
free(data);
counts[i] = count;
}
return 0;
}
replace_in_files.h 20 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/replace-text-in-many-files/.
#ifndef REPLACE_IN_FILES_H
#define REPLACE_IN_FILES_H
#include <stddef.h>
// Replaces each instance of old_text with new_text in each of the n files in
// paths, and puts the number of instances in each file in counts. old_text and
// new_text are plain text, not patterns. Instances do not overlap. A file with
// no instance is not written. A changed file goes to a new file in the same
// directory, and rename puts it in the place of the old one. The files are
// done in order. Returns 0, or -1 with errno set at the first error: the files
// before have the new text, and the files after do not change. An empty
// old_text sets errno to EINVAL.
int replace_in_files(const char *const paths[], size_t n, const char *old_text, const char *new_text,
size_t counts[]);
#endif
test_replace_in_files.c 202 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/replace-text-in-many-files/.
#define _POSIX_C_SOURCE 200809L
#include "replace_in_files.h"
#include <dirent.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
static int failures = 0;
#define CHECK(cond, name) \
do { \
if (!(cond)) { \
fprintf(stderr, "FAIL %s: %s\n", name, #cond); \
failures++; \
} \
} while (0)
static char dir[64];
struct file {
const char *name, *before, *after;
};
struct test_case {
const char *name, *old_text, *new_text;
size_t n;
struct file files[2];
size_t want[2];
};
static void write_text(const char *path, const char *text) {
FILE *f = fopen(path, "wb");
fputs(text, f);
fclose(f);
}
// Returns the text of the file in a new buffer that the caller frees.
static char *read_text(const char *path) {
FILE *f = fopen(path, "rb");
if (f == NULL) {
return NULL;
}
char *buf = calloc(1 << 21, 1);
size_t n = fread(buf, 1, (1 << 21) - 1, f);
buf[n] = '\0';
fclose(f);
return buf;
}
static int count_files(void) {
DIR *d = opendir(dir);
int n = 0;
struct dirent *e;
while ((e = readdir(d)) != NULL) {
n += strcmp(e->d_name, ".") != 0 && strcmp(e->d_name, "..") != 0;
}
closedir(d);
return n;
}
static void remove_files(void) {
DIR *d = opendir(dir);
struct dirent *e;
char path[sizeof dir + sizeof e->d_name];
while ((e = readdir(d)) != NULL) {
if (strcmp(e->d_name, ".") != 0 && strcmp(e->d_name, "..") != 0) {
snprintf(path, sizeof path, "%s/%s", dir, e->d_name);
unlink(path);
}
}
closedir(d);
}
static const struct test_case cases[] = {
{"rosetta", "Goodbye London!", "Hello New York!", 2,
{{"a.txt", "Goodbye London!\n", "Hello New York!\n"},
{"b.txt", "Goodbye London! Goodbye London!\nGoodbye\n", "Hello New York! Hello New York!\nGoodbye\n"}},
{1, 2}},
{"some-files-match", "dog", "fox", 2, {{"a.txt", "cat\n", "cat\n"}, {"b.txt", "dog\ncat dog\n", "fox\ncat fox\n"}}, {0, 2}},
{"one-file", "1", "2", 1, {{"a.txt", "x = 1\ny = 1\n", "x = 2\ny = 2\n"}}, {2}},
{"no-files", "a", "b", 0, {{0}}, {0}},
{"no-match", "x", "y", 1, {{"a.txt", "abc\n", "abc\n"}}, {0}},
{"empty-file", "a", "b", 1, {{"a.txt", "", ""}}, {0}},
{"delete", "-", "", 1, {{"a.txt", "a-b-c\n", "abc\n"}}, {2}},
{"whole-file", "abc", "", 1, {{"a.txt", "abc", ""}}, {1}},
{"new-contains-old", "a", "aa", 1, {{"a.txt", "a a\n", "aa aa\n"}}, {2}},
{"overlapping", "aa", "b", 1, {{"a.txt", "aaa\n", "ba\n"}}, {1}},
{"adjacent", "aa", "b", 1, {{"a.txt", "aaaa\n", "bb\n"}}, {2}},
{"special-chars", "1.5", "\\&$1 $& [x]", 1, {{"a.txt", "1.5 and 125\n", "\\&$1 $& [x] and 125\n"}}, {1}},
{"glob-chars", "*.txt", "?", 1, {{"a.txt", "a.txt *.txt\n", "a.txt ?\n"}}, {1}},
{"across-lines", "end\nstart", "end start", 1, {{"a.txt", "end\nstart\n", "end start\n"}}, {1}},
{"lf-to-crlf", "\n", "\r\n", 1, {{"a.txt", "a\nb\n", "a\r\nb\r\n"}}, {2}},
{"crlf", "a", "c", 1, {{"a.txt", "a\r\nb\r\n", "c\r\nb\r\n"}}, {1}},
{"no-final-newline", "b", "c", 1, {{"a.txt", "a b", "a c"}}, {1}},
{"non-ascii", "\xc3\xa9", "e", 1, {{"a.txt", "caf\xc3\xa9" ", cafe\n", "cafe, cafe\n"}}, {1}},
{"case-sensitive", "hello", "bye", 1, {{"a.txt", "Hello hello\n", "Hello bye\n"}}, {1}},
};
int main(void) {
// mkdtemp is not visible on all systems with _POSIX_C_SOURCE, so the test
// makes its own directory.
snprintf(dir, sizeof dir, "/tmp/replace-in-files-%ld", (long)getpid());
if (mkdir(dir, 0700) != 0) {
perror(dir);
return 1;
}
char path[2][128];
const char *paths[3];
size_t counts[3];
for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) {
const struct test_case *c = &cases[i];
for (size_t j = 0; j < c->n; j++) {
snprintf(path[j], sizeof path[j], "%s/%s", dir, c->files[j].name);
write_text(path[j], c->files[j].before);
paths[j] = path[j];
}
int r = replace_in_files(paths, c->n, c->old_text, c->new_text, counts);
CHECK(r == 0, c->name);
for (size_t j = 0; j < c->n; j++) {
CHECK(counts[j] == c->want[j], c->name);
char *got = read_text(path[j]);
CHECK(got != NULL && strcmp(got, c->files[j].after) == 0, c->name);
free(got);
}
// No temporary file stays in the directory.
CHECK(count_files() == (int)c->n, c->name);
remove_files();
}
// 100000 lines: "line 0" to "line 99999" become "L0" to "L99999".
snprintf(path[0], sizeof path[0], "%s/many.txt", dir);
paths[0] = path[0];
FILE *f = fopen(path[0], "wb");
for (int i = 0; i < 100000; i++) {
fprintf(f, "line %d\n", i);
}
fclose(f);
CHECK(replace_in_files(paths, 1, "line ", "L", counts) == 0 && counts[0] == 100000, "many-lines");
char *got = read_text(path[0]);
char *want = calloc(1 << 21, 1);
for (int i = 0, n = 0; i < 100000; i++) {
n += snprintf(want + n, (size_t)((1 << 21) - n), "L%d\n", i);
}
CHECK(got != NULL && strcmp(got, want) == 0, "many-lines");
free(want);
free(got);
remove_files();
// The permissions stay, and a file with no instance is not written.
snprintf(path[0], sizeof path[0], "%s/a.txt", dir);
write_text(path[0], "a\n");
chmod(path[0], 0640);
CHECK(replace_in_files(paths, 1, "a", "b", counts) == 0 && counts[0] == 1, "keeps-the-permissions");
struct stat st;
CHECK(stat(path[0], &st) == 0 && (st.st_mode & 0777) == 0640, "keeps-the-permissions");
ino_t before = st.st_ino;
CHECK(replace_in_files(paths, 1, "x", "y", counts) == 0 && counts[0] == 0, "no-change");
CHECK(stat(path[0], &st) == 0 && st.st_ino == before, "no-change");
// Errors.
errno = 0;
CHECK(replace_in_files(paths, 1, "", "b", counts) == -1 && errno == EINVAL, "empty-old");
got = read_text(path[0]);
CHECK(got != NULL && strcmp(got, "b\n") == 0, "empty-old");
free(got);
remove_files();
snprintf(path[0], sizeof path[0], "%s/missing.txt", dir);
errno = 0;
CHECK(replace_in_files(paths, 1, "a", "b", counts) == -1 && errno == ENOENT, "not-found");
// The first error stops the function.
char a[128], missing[128], c[128];
snprintf(a, sizeof a, "%s/a.txt", dir);
snprintf(missing, sizeof missing, "%s/missing.txt", dir);
snprintf(c, sizeof c, "%s/c.txt", dir);
write_text(a, "a\n");
write_text(c, "a\n");
const char *stop[] = {a, missing, c};
CHECK(replace_in_files(stop, 3, "a", "b", counts) == -1 && errno == ENOENT, "stop");
got = read_text(a);
CHECK(got != NULL && strcmp(got, "b\n") == 0, "stop");
free(got);
got = read_text(c);
CHECK(got != NULL && strcmp(got, "a\n") == 0, "stop");
free(got);
remove_files();
rmdir(dir);
if (failures == 0) {
puts("ok");
}
return failures != 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/replace-text-in-many-files/.
using System.Text;
/// <summary>Replaces a text with another text in each file of a list.</summary>
public static class ReplaceInFiles
{
/// <summary>
/// Replaces each instance of oldText with newText in each file, and returns the number of
/// instances in each file. oldText and newText are plain text, not patterns. The code compares
/// the UTF-8 bytes of oldText with the bytes of each file, so an instance can contain LF bytes.
/// Instances do not overlap. A file with no instance is not written. A changed file goes to a
/// new file in the same directory, and File.Move puts it in the place of the old one. The files
/// are done in order, and the first error stops the method: the files before have the new
/// text, and the files after do not change.
/// </summary>
/// <exception cref="ArgumentException">oldText is empty.</exception>
/// <exception cref="FileNotFoundException">A file does not exist.</exception>
public static int[] Replace(IReadOnlyList<string> paths, string oldText, string newText)
{
ArgumentException.ThrowIfNullOrEmpty(oldText);
byte[] oldBytes = Encoding.UTF8.GetBytes(oldText);
byte[] newBytes = Encoding.UTF8.GetBytes(newText);
int[] counts = new int[paths.Count];
for (int i = 0; i < paths.Count; i++)
{
byte[] data = File.ReadAllBytes(paths[i]);
var output = new MemoryStream(data.Length);
int from = 0;
int at;
while ((at = data.AsSpan(from).IndexOf(oldBytes)) != -1)
{
output.Write(data, from, at);
output.Write(newBytes);
counts[i]++;
// The search goes on after the end of the instance.
from += at + oldBytes.Length;
}
if (counts[i] > 0)
{
output.Write(data, from, data.Length - from);
WriteAtomically(paths[i], output.ToArray());
}
}
return counts;
}
// Writes data to a new file next to path, and moves it over path.
private static void WriteAtomically(string path, byte[] data)
{
string dir = Path.GetDirectoryName(Path.GetFullPath(path))!;
string tmp = Path.Combine(dir, $".{Path.GetFileName(path)}.{Guid.NewGuid():N}.tmp");
try
{
// CreateNew fails if a file with the name exists.
using (var stream = new FileStream(tmp, FileMode.CreateNew, FileAccess.Write))
{
stream.Write(data);
// Flush(true) also writes the data from the operating system to the disk.
stream.Flush(true);
}
if (!OperatingSystem.IsWindows())
{
File.SetUnixFileMode(tmp, File.GetUnixFileMode(path));
}
File.Move(tmp, path, overwrite: true);
}
catch
{
File.Delete(tmp);
throw;
}
}
}
ReplaceInFilesTests.cs 112 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/replace-text-in-many-files/.
using System.Text;
using Xunit;
public sealed class ReplaceInFilesTests : IDisposable
{
private readonly string dir = Directory.CreateTempSubdirectory("replace-in-files-").FullName;
public void Dispose() => Directory.Delete(dir, recursive: true);
// Each file is (name, text before, text after).
public static TheoryData<string, string, string, (string, string, string)[], int[]> Cases => new()
{
{ "rosetta", "Goodbye London!", "Hello New York!", [("a.txt", "Goodbye London!\n", "Hello New York!\n"),
("b.txt", "Goodbye London! Goodbye London!\nGoodbye\n", "Hello New York! Hello New York!\nGoodbye\n")], [1, 2] },
{ "some-files-match", "dog", "fox", [("a.txt", "cat\n", "cat\n"), ("b.txt", "dog\ncat dog\n", "fox\ncat fox\n")], [0, 2] },
{ "one-file", "1", "2", [("a.txt", "x = 1\ny = 1\n", "x = 2\ny = 2\n")], [2] },
{ "no-files", "a", "b", [], [] },
{ "no-match", "x", "y", [("a.txt", "abc\n", "abc\n")], [0] },
{ "empty-file", "a", "b", [("a.txt", "", "")], [0] },
{ "delete", "-", "", [("a.txt", "a-b-c\n", "abc\n")], [2] },
{ "whole-file", "abc", "", [("a.txt", "abc", "")], [1] },
{ "new-contains-old", "a", "aa", [("a.txt", "a a\n", "aa aa\n")], [2] },
{ "overlapping", "aa", "b", [("a.txt", "aaa\n", "ba\n")], [1] },
{ "adjacent", "aa", "b", [("a.txt", "aaaa\n", "bb\n")], [2] },
{ "special-chars", "1.5", "\\&$1 $& [x]", [("a.txt", "1.5 and 125\n", "\\&$1 $& [x] and 125\n")], [1] },
{ "glob-chars", "*.txt", "?", [("a.txt", "a.txt *.txt\n", "a.txt ?\n")], [1] },
{ "across-lines", "end\nstart", "end start", [("a.txt", "end\nstart\n", "end start\n")], [1] },
{ "lf-to-crlf", "\n", "\r\n", [("a.txt", "a\nb\n", "a\r\nb\r\n")], [2] },
{ "crlf", "a", "c", [("a.txt", "a\r\nb\r\n", "c\r\nb\r\n")], [1] },
{ "no-final-newline", "b", "c", [("a.txt", "a b", "a c")], [1] },
{ "non-ascii", "\u00e9", "e", [("a.txt", "caf\u00e9, cafe\n", "cafe, cafe\n")], [1] },
{ "case-sensitive", "hello", "bye", [("a.txt", "Hello hello\n", "Hello bye\n")], [1] },
};
// UTF8Encoding(false) writes no byte order mark.
private static void Write(string path, string text) => File.WriteAllText(path, text, new UTF8Encoding(false));
[Theory]
[MemberData(nameof(Cases))]
public void Replace(string name, string oldText, string newText, (string, string, string)[] files, int[] want)
{
var paths = files.Select(f => Path.Combine(dir, f.Item1)).ToArray();
for (int i = 0; i < files.Length; i++)
{
Write(paths[i], files[i].Item2);
}
Assert.Equal(want, ReplaceInFiles.Replace(paths, oldText, newText));
for (int i = 0; i < files.Length; i++)
{
Assert.Equal(files[i].Item3, File.ReadAllText(paths[i], Encoding.UTF8));
}
// No temporary file stays in the directory.
Assert.Equal(files.Length, Directory.GetFiles(dir).Length);
_ = name;
}
private static string Lines(string prefix) =>
string.Concat(Enumerable.Range(0, 100000).Select(i => $"{prefix}{i}\n"));
[Fact]
public void ManyLines()
{
string path = Path.Combine(dir, "many.txt");
Write(path, Lines("line "));
Assert.Equal([100000], ReplaceInFiles.Replace([path], "line ", "L"));
Assert.Equal(Lines("L"), File.ReadAllText(path));
}
[Fact]
public void KeepsThePermissions()
{
if (OperatingSystem.IsWindows())
{
return;
}
string path = Path.Combine(dir, "a.txt");
Write(path, "a\n");
var mode = UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.GroupRead;
File.SetUnixFileMode(path, mode);
Assert.Equal([1], ReplaceInFiles.Replace([path], "a", "b"));
Assert.Equal(mode, File.GetUnixFileMode(path));
}
[Fact]
public void NotFound()
{
Assert.Throws<FileNotFoundException>(() => ReplaceInFiles.Replace([Path.Combine(dir, "missing.txt")], "a", "b"));
}
[Fact]
public void EmptyOld()
{
string path = Path.Combine(dir, "a.txt");
Write(path, "a\n");
Assert.Throws<ArgumentException>(() => ReplaceInFiles.Replace([path], "", "b"));
Assert.Equal("a\n", File.ReadAllText(path));
}
[Fact]
public void Stop()
{
string a = Path.Combine(dir, "a.txt"), c = Path.Combine(dir, "c.txt");
Write(a, "a\n");
Write(c, "a\n");
Assert.Throws<FileNotFoundException>(() => ReplaceInFiles.Replace([a, Path.Combine(dir, "missing.txt"), c], "a", "b"));
Assert.Equal("b\n", File.ReadAllText(a));
Assert.Equal("a\n", File.ReadAllText(c));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/replace-text-in-many-files/.
import { randomUUID } from "node:crypto";
import { chmodSync, closeSync, fsyncSync, openSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
import { basename, dirname, join } from "node:path";
// Replaces each instance of oldText with newText in each file, and returns the
// number of instances in each file. oldText and newText are plain text, not
// patterns. The code compares the UTF-8 bytes of oldText with the bytes of
// each file, so an instance can contain LF bytes. Instances do not overlap. A
// file with no instance is not written. A changed file goes to a new file in
// the same directory, and renameSync puts it in the place of the old one. The
// files are done in order, and the first error stops the function. Throws a
// RangeError if oldText is empty, and an error whose code is "ENOENT" if a
// file does not exist.
export function replaceInFiles(paths, oldText, newText) {
if (typeof oldText !== "string" || oldText.length === 0) {
throw new RangeError("oldText is empty");
}
const oldBytes = Buffer.from(oldText, "utf8");
const newBytes = Buffer.from(newText, "utf8");
const counts = [];
for (const path of paths) {
const data = readFileSync(path);
// Copy the bytes between the instances, and newBytes for each instance.
// The search goes on after the end of each instance.
const parts = [];
let from = 0;
let at;
while ((at = data.indexOf(oldBytes, from)) !== -1) {
parts.push(data.subarray(from, at), newBytes);
from = at + oldBytes.length;
}
const n = parts.length / 2;
if (n > 0) {
parts.push(data.subarray(from));
writeAtomically(path, Buffer.concat(parts));
}
counts.push(n);
}
return counts;
}
// Writes data to a new file next to path, and renames it over path.
function writeAtomically(path, data) {
const tmp = join(dirname(path), `.${basename(path)}.${randomUUID()}.tmp`);
try {
// "wx" fails if the file exists, so the code does not write over a file
// with the same name.
const fd = openSync(tmp, "wx", 0o600);
try {
writeFileSync(fd, data);
fsyncSync(fd);
} finally {
closeSync(fd);
}
chmodSync(tmp, statSync(path).mode & 0o7777);
renameSync(tmp, path);
} catch (err) {
rmSync(tmp, { force: true });
throw err;
}
}
replaceInFiles.test.js 77 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/replace-text-in-many-files/.
import assert from "node:assert/strict";
import { chmodSync, cpSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { basename, join } from "node:path";
import { fileURLToPath } from "node:url";
import { after, test } from "node:test";
import { replaceInFiles } from "./replaceInFiles.js";
const node = fileURLToPath(new URL("../../", import.meta.url));
const root = mkdtempSync(join(tmpdir(), "replace-in-files-"));
after(() => rmSync(root, { recursive: true }));
function load(name) {
return readFileSync(join(node, "cases", name), "utf8")
.split("\n")
.filter((line) => line.trim() !== "")
.map((line) => JSON.parse(line));
}
// Copies fixtures/NAME to a new directory and returns the directory.
function copyCase(name) {
const dir = join(mkdtempSync(join(root, "case-")), name);
const src = join(node, "fixtures", name);
if (existsSync(src)) cpSync(src, dir, { recursive: true });
else mkdirSync(dir);
return dir;
}
for (const c of [...load("basic.jsonl"), ...load("edge.jsonl")]) {
test(c.name, () => {
const dir = copyCase(c.name);
const paths = c.args.paths.map((p) => join(dir, basename(p)));
assert.deepEqual(replaceInFiles(paths, c.args.old, c.args.new), c.expect);
for (const p of paths) {
assert.deepEqual(readFileSync(p), readFileSync(join(node, "fixtures", c.name + ".after", basename(p))));
}
// No temporary file stays in the directory.
assert.deepEqual(readdirSync(dir).sort(), paths.map((p) => basename(p)).sort());
});
}
test("many-lines", () => {
const path = join(mkdtempSync(join(root, "case-")), "many.txt");
const lines = (prefix) => Array.from({ length: 100000 }, (_, i) => `${prefix}${i}\n`).join("");
writeFileSync(path, lines("line "));
assert.deepEqual(replaceInFiles([path], "line ", "L"), [100000]);
assert.equal(readFileSync(path, "utf8"), lines("L"));
});
test("keeps-the-permissions", { skip: process.platform === "win32" }, () => {
const path = join(mkdtempSync(join(root, "case-")), "a.txt");
writeFileSync(path, "a\n");
chmodSync(path, 0o640);
assert.deepEqual(replaceInFiles([path], "a", "b"), [1]);
assert.equal(statSync(path).mode & 0o777, 0o640);
});
test("errors", () => {
assert.deepEqual(load("errors.jsonl").map((c) => c.name), ["not-found", "empty-old", "stop"]);
assert.throws(() => replaceInFiles([join(root, "missing.txt")], "a", "b"), { code: "ENOENT" });
const path = join(mkdtempSync(join(root, "case-")), "a.txt");
writeFileSync(path, "a\n");
assert.throws(() => replaceInFiles([path], "", "b"), RangeError);
assert.equal(readFileSync(path, "utf8"), "a\n");
});
test("stop", () => {
const dir = copyCase("stop");
const names = ["a.txt", "missing.txt", "c.txt"];
assert.throws(() => replaceInFiles(names.map((n) => join(dir, n)), "a", "b"), { code: "ENOENT" });
for (const n of ["a.txt", "c.txt"]) {
assert.deepEqual(readFileSync(join(dir, n)), readFileSync(join(node, "fixtures", "stop.after", n)));
}
});
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/replace-text-in-many-files/.
import { randomUUID } from "node:crypto";
import { chmodSync, closeSync, fsyncSync, openSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
import { basename, dirname, join } from "node:path";
// Replaces each instance of oldText with newText in each file, and returns the
// number of instances in each file. oldText and newText are plain text, not
// patterns. The code compares the UTF-8 bytes of oldText with the bytes of
// each file, so an instance can contain LF bytes. Instances do not overlap. A
// file with no instance is not written. A changed file goes to a new file in
// the same directory, and renameSync puts it in the place of the old one. The
// files are done in order, and the first error stops the function. Throws a
// RangeError if oldText is empty, and an error whose code is "ENOENT" if a
// file does not exist.
export function replaceInFiles(paths: Iterable<string>, oldText: string, newText: string): number[] {
if (oldText.length === 0) {
throw new RangeError("oldText is empty");
}
const oldBytes = Buffer.from(oldText, "utf8");
const newBytes = Buffer.from(newText, "utf8");
const counts: number[] = [];
for (const path of paths) {
const data = readFileSync(path);
// Copy the bytes between the instances, and newBytes for each instance.
// The search goes on after the end of each instance.
const parts: Buffer[] = [];
let from = 0;
let at: number;
while ((at = data.indexOf(oldBytes, from)) !== -1) {
parts.push(data.subarray(from, at), newBytes);
from = at + oldBytes.length;
}
const n = parts.length / 2;
if (n > 0) {
parts.push(data.subarray(from));
writeAtomically(path, Buffer.concat(parts));
}
counts.push(n);
}
return counts;
}
// Writes data to a new file next to path, and renames it over path.
function writeAtomically(path: string, data: Buffer): void {
const tmp = join(dirname(path), `.${basename(path)}.${randomUUID()}.tmp`);
try {
// "wx" fails if the file exists, so the code does not write over a file
// with the same name.
const fd = openSync(tmp, "wx", 0o600);
try {
writeFileSync(fd, data);
fsyncSync(fd);
} finally {
closeSync(fd);
}
chmodSync(tmp, statSync(path).mode & 0o7777);
renameSync(tmp, path);
} catch (err) {
rmSync(tmp, { force: true });
throw err;
}
}
replaceInFiles.test.ts 83 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/replace-text-in-many-files/.
import assert from "node:assert/strict";
import { chmodSync, cpSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { basename, join } from "node:path";
import { fileURLToPath } from "node:url";
import { after, test } from "node:test";
import { replaceInFiles } from "./replaceInFiles.ts";
const node = fileURLToPath(new URL("../../", import.meta.url));
const root = mkdtempSync(join(tmpdir(), "replace-in-files-"));
after(() => rmSync(root, { recursive: true }));
interface Case {
name: string;
args: { paths: string[]; old: string; new: string };
expect: number[];
}
function load(name: string): Case[] {
return readFileSync(join(node, "cases", name), "utf8")
.split("\n")
.filter((line) => line.trim() !== "")
.map((line) => JSON.parse(line) as Case);
}
// Copies fixtures/NAME to a new directory and returns the directory.
function copyCase(name: string): string {
const dir = join(mkdtempSync(join(root, "case-")), name);
const src = join(node, "fixtures", name);
if (existsSync(src)) cpSync(src, dir, { recursive: true });
else mkdirSync(dir);
return dir;
}
for (const c of [...load("basic.jsonl"), ...load("edge.jsonl")]) {
test(c.name, () => {
const dir = copyCase(c.name);
const paths = c.args.paths.map((p) => join(dir, basename(p)));
assert.deepEqual(replaceInFiles(paths, c.args.old, c.args.new), c.expect);
for (const p of paths) {
assert.deepEqual(readFileSync(p), readFileSync(join(node, "fixtures", c.name + ".after", basename(p))));
}
// No temporary file stays in the directory.
assert.deepEqual(readdirSync(dir).sort(), paths.map((p) => basename(p)).sort());
});
}
test("many-lines", () => {
const path = join(mkdtempSync(join(root, "case-")), "many.txt");
const lines = (prefix: string) => Array.from({ length: 100000 }, (_, i) => `${prefix}${i}\n`).join("");
writeFileSync(path, lines("line "));
assert.deepEqual(replaceInFiles([path], "line ", "L"), [100000]);
assert.equal(readFileSync(path, "utf8"), lines("L"));
});
test("keeps-the-permissions", { skip: process.platform === "win32" }, () => {
const path = join(mkdtempSync(join(root, "case-")), "a.txt");
writeFileSync(path, "a\n");
chmodSync(path, 0o640);
assert.deepEqual(replaceInFiles([path], "a", "b"), [1]);
assert.equal(statSync(path).mode & 0o777, 0o640);
});
test("errors", () => {
assert.deepEqual(load("errors.jsonl").map((c) => c.name), ["not-found", "empty-old", "stop"]);
assert.throws(() => replaceInFiles([join(root, "missing.txt")], "a", "b"), { code: "ENOENT" });
const path = join(mkdtempSync(join(root, "case-")), "a.txt");
writeFileSync(path, "a\n");
assert.throws(() => replaceInFiles([path], "", "b"), RangeError);
assert.equal(readFileSync(path, "utf8"), "a\n");
});
test("stop", () => {
const dir = copyCase("stop");
const names = ["a.txt", "missing.txt", "c.txt"];
assert.throws(() => replaceInFiles(names.map((n) => join(dir, n)), "a", "b"), { code: "ENOENT" });
for (const n of ["a.txt", "c.txt"]) {
assert.deepEqual(readFileSync(join(dir, n)), readFileSync(join(node, "fixtures", "stop.after", n)));
}
});
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/replace-text-in-many-files/.
// Package replaceinfiles replaces a text with another text in each file of a
// list.
package replaceinfiles
import (
"bytes"
"errors"
"os"
"path/filepath"
)
// ErrEmptyOld is the error when the text to find is empty.
var ErrEmptyOld = errors.New("replaceinfiles: the text to find is empty")
// ReplaceInFiles replaces each instance of old with new in each file, and
// returns the number of instances in each file. old and new are plain text,
// not patterns, and an instance can contain LF bytes. Instances do not
// overlap. A file with no instance is not written. A changed file goes to a
// new file in the same directory, and os.Rename puts it in the place of the
// old one. The files are done in order, and the first error stops the
// function: the files before have the new text, and the files after do not
// change. A missing file gives an error for which errors.Is(err,
// fs.ErrNotExist) is true.
func ReplaceInFiles(paths []string, old, new string) ([]int, error) {
if old == "" {
return nil, ErrEmptyOld
}
counts := make([]int, 0, len(paths))
for _, path := range paths {
data, err := os.ReadFile(path)
if err != nil {
return nil, err
}
// Count and ReplaceAll both find instances that do not overlap, from
// left to right, so the count is the number of replacements.
n := bytes.Count(data, []byte(old))
if n > 0 {
if err := writeAtomically(path, bytes.ReplaceAll(data, []byte(old), []byte(new))); err != nil {
return nil, err
}
}
counts = append(counts, n)
}
return counts, nil
}
// writeAtomically writes data to a new file next to path, and renames it over
// path.
func writeAtomically(path string, data []byte) (err error) {
info, err := os.Stat(path)
if err != nil {
return err
}
tmp, err := os.CreateTemp(filepath.Dir(path), "."+filepath.Base(path)+".*.tmp")
if err != nil {
return err
}
// On each return before the rename, close and remove the new file.
renamed := false
defer func() {
if !renamed {
tmp.Close()
os.Remove(tmp.Name())
}
}()
if _, err := tmp.Write(data); err != nil {
return err
}
// CreateTemp makes the file with mode 0600.
if err := tmp.Chmod(info.Mode().Perm()); err != nil {
return err
}
if err := tmp.Sync(); err != nil {
return err
}
if err := tmp.Close(); err != nil {
return err
}
if err := os.Rename(tmp.Name(), path); err != nil {
return err
}
renamed = true
return nil
}
replace_in_files_test.go 167 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/replace-text-in-many-files/.
package replaceinfiles
import (
"errors"
"io/fs"
"os"
"path/filepath"
"runtime"
"slices"
"strconv"
"strings"
"testing"
)
type file struct{ name, before, after string }
func TestReplaceInFiles(t *testing.T) {
cases := []struct {
name string
old, new string
files []file
want []int
}{
{"rosetta", "Goodbye London!", "Hello New York!", []file{
{"a.txt", "Goodbye London!\n", "Hello New York!\n"},
{"b.txt", "Goodbye London! Goodbye London!\nGoodbye\n", "Hello New York! Hello New York!\nGoodbye\n"},
}, []int{1, 2}},
{"some-files-match", "dog", "fox", []file{{"a.txt", "cat\n", "cat\n"}, {"b.txt", "dog\ncat dog\n", "fox\ncat fox\n"}}, []int{0, 2}},
{"one-file", "1", "2", []file{{"a.txt", "x = 1\ny = 1\n", "x = 2\ny = 2\n"}}, []int{2}},
{"no-files", "a", "b", nil, []int{}},
{"no-match", "x", "y", []file{{"a.txt", "abc\n", "abc\n"}}, []int{0}},
{"empty-file", "a", "b", []file{{"a.txt", "", ""}}, []int{0}},
{"delete", "-", "", []file{{"a.txt", "a-b-c\n", "abc\n"}}, []int{2}},
{"whole-file", "abc", "", []file{{"a.txt", "abc", ""}}, []int{1}},
{"new-contains-old", "a", "aa", []file{{"a.txt", "a a\n", "aa aa\n"}}, []int{2}},
{"overlapping", "aa", "b", []file{{"a.txt", "aaa\n", "ba\n"}}, []int{1}},
{"adjacent", "aa", "b", []file{{"a.txt", "aaaa\n", "bb\n"}}, []int{2}},
{"special-chars", "1.5", `\&$1 $& [x]`, []file{{"a.txt", "1.5 and 125\n", `\&$1 $& [x]` + " and 125\n"}}, []int{1}},
{"glob-chars", "*.txt", "?", []file{{"a.txt", "a.txt *.txt\n", "a.txt ?\n"}}, []int{1}},
{"across-lines", "end\nstart", "end start", []file{{"a.txt", "end\nstart\n", "end start\n"}}, []int{1}},
{"lf-to-crlf", "\n", "\r\n", []file{{"a.txt", "a\nb\n", "a\r\nb\r\n"}}, []int{2}},
{"crlf", "a", "c", []file{{"a.txt", "a\r\nb\r\n", "c\r\nb\r\n"}}, []int{1}},
{"no-final-newline", "b", "c", []file{{"a.txt", "a b", "a c"}}, []int{1}},
{"non-ascii", "\u00e9", "e", []file{{"a.txt", "caf\u00e9, cafe\n", "cafe, cafe\n"}}, []int{1}},
{"case-sensitive", "hello", "bye", []file{{"a.txt", "Hello hello\n", "Hello bye\n"}}, []int{1}},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
dir := t.TempDir()
paths := []string{}
for _, f := range c.files {
p := filepath.Join(dir, f.name)
if err := os.WriteFile(p, []byte(f.before), 0o644); err != nil {
t.Fatal(err)
}
paths = append(paths, p)
}
got, err := ReplaceInFiles(paths, c.old, c.new)
if err != nil || !slices.Equal(got, c.want) {
t.Fatalf("got %v, %v; want %v", got, err, c.want)
}
for _, f := range c.files {
data, err := os.ReadFile(filepath.Join(dir, f.name))
if err != nil || string(data) != f.after {
t.Errorf("%s after: got %q, %v; want %q", f.name, data, err, f.after)
}
}
// No temporary file stays in the directory.
if entries, _ := os.ReadDir(dir); len(entries) != len(c.files) {
t.Errorf("%d files in the directory, want %d", len(entries), len(c.files))
}
})
}
}
func lines(prefix string) string {
var b strings.Builder
for i := range 100000 {
b.WriteString(prefix + strconv.Itoa(i) + "\n")
}
return b.String()
}
func TestManyLines(t *testing.T) {
path := filepath.Join(t.TempDir(), "many.txt")
if err := os.WriteFile(path, []byte(lines("line ")), 0o644); err != nil {
t.Fatal(err)
}
got, err := ReplaceInFiles([]string{path}, "line ", "L")
if err != nil || !slices.Equal(got, []int{100000}) {
t.Fatalf("got %v, %v", got, err)
}
if data, _ := os.ReadFile(path); string(data) != lines("L") {
t.Error("the file after the call is wrong")
}
}
func TestKeepsThePermissions(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("no Unix permissions")
}
path := filepath.Join(t.TempDir(), "a.txt")
if err := os.WriteFile(path, []byte("a\n"), 0o600); err != nil {
t.Fatal(err)
}
if err := os.Chmod(path, 0o640); err != nil {
t.Fatal(err)
}
if _, err := ReplaceInFiles([]string{path}, "a", "b"); err != nil {
t.Fatal(err)
}
if info, _ := os.Stat(path); info.Mode().Perm() != 0o640 {
t.Errorf("mode %v, want 0640", info.Mode().Perm())
}
}
func TestNoMatchDoesNotWrite(t *testing.T) {
path := filepath.Join(t.TempDir(), "a.txt")
if err := os.WriteFile(path, []byte("a\n"), 0o644); err != nil {
t.Fatal(err)
}
before, _ := os.Stat(path)
if got, err := ReplaceInFiles([]string{path}, "x", "y"); err != nil || !slices.Equal(got, []int{0}) {
t.Fatalf("got %v, %v", got, err)
}
if after, _ := os.Stat(path); !os.SameFile(before, after) {
t.Error("the file was written again")
}
}
func TestErrors(t *testing.T) {
dir := t.TempDir()
if _, err := ReplaceInFiles([]string{filepath.Join(dir, "missing.txt")}, "a", "b"); !errors.Is(err, fs.ErrNotExist) {
t.Errorf("not-found: got %v", err)
}
path := filepath.Join(dir, "a.txt")
if err := os.WriteFile(path, []byte("a\n"), 0o644); err != nil {
t.Fatal(err)
}
if _, err := ReplaceInFiles([]string{path}, "", "b"); !errors.Is(err, ErrEmptyOld) {
t.Errorf("empty-old: got %v", err)
}
if data, _ := os.ReadFile(path); string(data) != "a\n" {
t.Errorf("empty-old changed the file: %q", data)
}
}
func TestStop(t *testing.T) {
dir := t.TempDir()
for _, name := range []string{"a.txt", "c.txt"} {
if err := os.WriteFile(filepath.Join(dir, name), []byte("a\n"), 0o644); err != nil {
t.Fatal(err)
}
}
paths := []string{filepath.Join(dir, "a.txt"), filepath.Join(dir, "missing.txt"), filepath.Join(dir, "c.txt")}
if _, err := ReplaceInFiles(paths, "a", "b"); !errors.Is(err, fs.ErrNotExist) {
t.Fatalf("got %v", err)
}
for name, want := range map[string]string{"a.txt": "b\n", "c.txt": "a\n"} {
if data, _ := os.ReadFile(filepath.Join(dir, name)); string(data) != want {
t.Errorf("%s: got %q, want %q", name, data, want)
}
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/replace-text-in-many-files/.
//! Replaces a text with another text in each file of a list.
use std::fs::{self, File, OpenOptions};
use std::io::{self, ErrorKind, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
/// Replaces each instance of `old` with `new` in each file, and returns the
/// number of instances in each file.
///
/// `old` and `new` are plain text, not patterns, and an instance can contain
/// LF bytes. Instances do not overlap. A file with no instance is not written.
/// A changed file goes to a new file in the same directory, and `fs::rename`
/// puts it in the place of the old one. The files are done in order, and the
/// first error stops the function: the files before have the new text, and
/// the files after do not change. An empty `old` gives an error of kind
/// `InvalidInput`, and a missing file gives an error of kind `NotFound`.
pub fn replace_in_files<P: AsRef<Path>>(
paths: &[P],
old: &str,
new: &str,
) -> io::Result<Vec<usize>> {
if old.is_empty() {
return Err(io::Error::new(ErrorKind::InvalidInput, "old is empty"));
}
let mut counts = Vec::with_capacity(paths.len());
for path in paths {
let path = path.as_ref();
let data = fs::read(path)?;
let (replaced, n) = replace(&data, old.as_bytes(), new.as_bytes());
if n > 0 {
write_atomically(path, &replaced)?;
}
counts.push(n);
}
Ok(counts)
}
/// Returns `data` with each instance of `old` changed to `new`, and the number
/// of instances. After an instance, the search goes on after its end, so
/// instances do not overlap.
fn replace(data: &[u8], old: &[u8], new: &[u8]) -> (Vec<u8>, usize) {
let mut out = Vec::with_capacity(data.len());
let mut n = 0;
let mut from = 0;
while let Some(at) = find(&data[from..], old) {
out.extend_from_slice(&data[from..from + at]);
out.extend_from_slice(new);
from += at + old.len();
n += 1;
}
out.extend_from_slice(&data[from..]);
(out, n)
}
/// Returns the index of the first instance of `needle` in `haystack`.
fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
haystack.windows(needle.len()).position(|w| w == needle)
}
/// Writes `data` to a new file next to `path`, and renames it over `path`.
fn write_atomically(path: &Path, data: &[u8]) -> io::Result<()> {
let permissions = fs::metadata(path)?.permissions();
let (tmp_path, mut tmp) = create_temp(path)?;
let result = (|| {
tmp.write_all(data)?;
// The new file has the default permissions, so it gets the old ones.
tmp.set_permissions(permissions)?;
tmp.sync_all()?;
fs::rename(&tmp_path, path)
})();
if result.is_err() {
let _ = fs::remove_file(&tmp_path);
}
result
}
/// Creates a new file next to `path` with a name that no file has.
fn create_temp(path: &Path) -> io::Result<(PathBuf, File)> {
static NEXT: AtomicU64 = AtomicU64::new(0);
let dir = path.parent().unwrap_or(Path::new(""));
let name = path.file_name().unwrap_or_default().to_string_lossy();
loop {
let n = NEXT.fetch_add(1, Ordering::Relaxed);
let tmp_path = dir.join(format!(".{name}.{}.{n}.tmp", std::process::id()));
// create_new fails if the file exists, so the code does not write
// over a file with the same name.
match OpenOptions::new()
.write(true)
.create_new(true)
.open(&tmp_path)
{
Ok(file) => return Ok((tmp_path, file)),
Err(e) if e.kind() == ErrorKind::AlreadyExists => continue,
Err(e) => return Err(e),
}
}
}
tests/replace_in_files_test.rs 216 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/replace-text-in-many-files/.
use std::fs;
use std::io::ErrorKind;
use std::path::PathBuf;
use std::sync::atomic::{AtomicU32, Ordering};
use algo_replace_in_files::replace_in_files;
/// (file name, the text before, the text after)
type File<'a> = (&'a str, &'a str, &'a str);
/// (name, old, new, the files, the result)
type Case<'a> = (&'a str, &'a str, &'a str, &'a [File<'a>], &'a [usize]);
/// Makes a new directory for one test.
fn temp_dir() -> PathBuf {
static NEXT: AtomicU32 = AtomicU32::new(0);
let n = NEXT.fetch_add(1, Ordering::Relaxed);
let dir = std::env::temp_dir().join(format!("replace-in-files-{}-{n}", std::process::id()));
fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn cases() {
let cases: [Case; 19] = [
(
"rosetta",
"Goodbye London!",
"Hello New York!",
&[
("a.txt", "Goodbye London!\n", "Hello New York!\n"),
(
"b.txt",
"Goodbye London! Goodbye London!\nGoodbye\n",
"Hello New York! Hello New York!\nGoodbye\n",
),
],
&[1, 2],
),
(
"some-files-match",
"dog",
"fox",
&[
("a.txt", "cat\n", "cat\n"),
("b.txt", "dog\ncat dog\n", "fox\ncat fox\n"),
],
&[0, 2],
),
(
"one-file",
"1",
"2",
&[("a.txt", "x = 1\ny = 1\n", "x = 2\ny = 2\n")],
&[2],
),
("no-files", "a", "b", &[], &[]),
("no-match", "x", "y", &[("a.txt", "abc\n", "abc\n")], &[0]),
("empty-file", "a", "b", &[("a.txt", "", "")], &[0]),
("delete", "-", "", &[("a.txt", "a-b-c\n", "abc\n")], &[2]),
("whole-file", "abc", "", &[("a.txt", "abc", "")], &[1]),
(
"new-contains-old",
"a",
"aa",
&[("a.txt", "a a\n", "aa aa\n")],
&[2],
),
(
"overlapping",
"aa",
"b",
&[("a.txt", "aaa\n", "ba\n")],
&[1],
),
("adjacent", "aa", "b", &[("a.txt", "aaaa\n", "bb\n")], &[2]),
(
"special-chars",
"1.5",
r"\&$1 $& [x]",
&[("a.txt", "1.5 and 125\n", "\\&$1 $& [x] and 125\n")],
&[1],
),
(
"glob-chars",
"*.txt",
"?",
&[("a.txt", "a.txt *.txt\n", "a.txt ?\n")],
&[1],
),
(
"across-lines",
"end\nstart",
"end start",
&[("a.txt", "end\nstart\n", "end start\n")],
&[1],
),
(
"lf-to-crlf",
"\n",
"\r\n",
&[("a.txt", "a\nb\n", "a\r\nb\r\n")],
&[2],
),
(
"crlf",
"a",
"c",
&[("a.txt", "a\r\nb\r\n", "c\r\nb\r\n")],
&[1],
),
(
"no-final-newline",
"b",
"c",
&[("a.txt", "a b", "a c")],
&[1],
),
(
"non-ascii",
"\u{e9}",
"e",
&[("a.txt", "caf\u{e9}, cafe\n", "cafe, cafe\n")],
&[1],
),
(
"case-sensitive",
"hello",
"bye",
&[("a.txt", "Hello hello\n", "Hello bye\n")],
&[1],
),
];
for (name, old, new, files, want) in cases {
let dir = temp_dir();
let paths: Vec<PathBuf> = files.iter().map(|f| dir.join(f.0)).collect();
for (f, p) in files.iter().zip(&paths) {
fs::write(p, f.1).unwrap();
}
assert_eq!(replace_in_files(&paths, old, new).unwrap(), want, "{name}");
for (f, p) in files.iter().zip(&paths) {
assert_eq!(fs::read_to_string(p).unwrap(), f.2, "{name} after");
}
// No temporary file stays in the directory.
assert_eq!(
fs::read_dir(&dir).unwrap().count(),
files.len(),
"{name} files"
);
fs::remove_dir_all(&dir).unwrap();
}
}
#[test]
fn many_lines() {
let lines = |prefix: &str| {
(0..100000)
.map(|i| format!("{prefix}{i}\n"))
.collect::<String>()
};
let dir = temp_dir();
let path = dir.join("many.txt");
fs::write(&path, lines("line ")).unwrap();
assert_eq!(replace_in_files(&[&path], "line ", "L").unwrap(), [100000]);
assert_eq!(fs::read_to_string(&path).unwrap(), lines("L"));
fs::remove_dir_all(&dir).unwrap();
}
#[cfg(unix)]
#[test]
fn keeps_the_permissions() {
use std::os::unix::fs::PermissionsExt;
let dir = temp_dir();
let path = dir.join("a.txt");
fs::write(&path, "a\n").unwrap();
fs::set_permissions(&path, fs::Permissions::from_mode(0o640)).unwrap();
assert_eq!(replace_in_files(&[&path], "a", "b").unwrap(), [1]);
assert_eq!(
fs::metadata(&path).unwrap().permissions().mode() & 0o777,
0o640
);
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn errors() {
let dir = temp_dir();
let err = replace_in_files(&[dir.join("missing.txt")], "a", "b").unwrap_err();
assert_eq!(err.kind(), ErrorKind::NotFound);
let path = dir.join("a.txt");
fs::write(&path, "a\n").unwrap();
let err = replace_in_files(&[&path], "", "b").unwrap_err();
assert_eq!(err.kind(), ErrorKind::InvalidInput);
assert_eq!(fs::read_to_string(&path).unwrap(), "a\n");
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn stop() {
let dir = temp_dir();
fs::write(dir.join("a.txt"), "a\n").unwrap();
fs::write(dir.join("c.txt"), "a\n").unwrap();
let paths = [
dir.join("a.txt"),
dir.join("missing.txt"),
dir.join("c.txt"),
];
let err = replace_in_files(&paths, "a", "b").unwrap_err();
assert_eq!(err.kind(), ErrorKind::NotFound);
assert_eq!(fs::read_to_string(dir.join("a.txt")).unwrap(), "b\n");
assert_eq!(fs::read_to_string(dir.join("c.txt")).unwrap(), "a\n");
fs::remove_dir_all(&dir).unwrap();
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/replace-text-in-many-files/.
# The awk program reads a file line by line and writes the new text to the
# file OUT. It keeps the last length(OLD) - 1 bytes in buf, because an instance
# can start there and go on in the next line. index() finds plain text, not a
# pattern. ENVIRON gives the texts as they are: awk -v changes backslashes.
_replace_in_files_awk='
function flush(keep, i) {
while ((i = index(buf, old)) > 0) {
printf "%s%s", substr(buf, 1, i - 1), new > out
buf = substr(buf, i + n)
count++
}
if (length(buf) > keep) {
printf "%s", substr(buf, 1, length(buf) - keep) > out
buf = substr(buf, length(buf) - keep + 1)
}
}
BEGIN { old = ENVIRON["OLD"]; new = ENVIRON["NEW"]; out = ENVIRON["OUT"]; n = length(old) }
{ buf = buf (NR > 1 ? "\n" : "") $0; flush(n - 1) }
END { if (ENVIRON["LAST_LF"] == 1) buf = buf "\n"; flush(0); print count + 0 }
'
# replace_in_files OLD NEW FILE...
# Replaces each instance of OLD with NEW in each FILE, and prints the number of
# instances in each file, one number on each line. OLD and NEW are plain text,
# not patterns, and they can contain LF. Instances do not overlap. A file with
# no instance is not written. A changed file goes to a new file in the same
# directory, and mv puts it in the place of the old one. The files are done in
# order. Returns 2 with a message if OLD is empty or a file cannot be read or
# written, and the files after it do not change. NUL bytes are not supported.
replace_in_files() {
local old=$1 new=$2 file tmp count last_lf
shift 2
if [[ -z $old ]]; then
printf 'replace_in_files: OLD is empty\n' >&2
return 2
fi
for file in "$@"; do
[[ -f $file && -r $file ]] || { printf 'replace_in_files: cannot read %s\n' "$file" >&2; return 2; }
# awk does not tell if the last line ends with LF. $(...) removes a final
# LF, so the result is empty if the last byte is LF.
last_lf=0
if [[ -s $file && -z $(tail -c 1 -- "$file") ]]; then last_lf=1; fi
tmp=$(mktemp "$file.XXXXXX") || return 2
# cp -p gives the new file the permissions of the old one, and awk keeps them.
# With LC_ALL=C, awk counts bytes, not characters.
if ! { cp -p -- "$file" "$tmp" &&
count=$(LC_ALL=C OLD=$old NEW=$new OUT=$tmp LAST_LF=$last_lf awk "$_replace_in_files_awk" "$file"); }; then
rm -f -- "$tmp"
return 2
fi
if ((count == 0)); then
rm -f -- "$tmp"
elif ! mv -f -- "$tmp" "$file"; then
rm -f -- "$tmp"
return 2
fi
echo "$count"
done
}
test_replace_in_files.bats 97 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/replace-text-in-many-files/.
bats_require_minimum_version 1.5.0
setup() {
source "$BATS_TEST_DIRNAME/replace_in_files.sh"
dir="$BATS_TEST_TMPDIR/case"
mkdir -p "$dir"
file="$dir/a.txt"
}
# The x keeps a final LF, which $(...) removes.
same() { # same FILE BYTES
[ "$(cat "$1"; printf x)" = "$(printf '%bx' "$2")" ]
}
check() { # check OLD NEW BEFORE WANT AFTER
printf '%b' "$3" >"$file"
[ "$(replace_in_files "$1" "$2" "$file")" = "$4" ]
same "$file" "$5"
# No temporary file stays in the directory.
[ "$(ls -A "$dir")" = "a.txt" ]
}
@test "one-file" { check 1 2 'x = 1\ny = 1\n' 2 'x = 2\ny = 2\n'; }
@test "no-match" { check x y 'abc\n' 0 'abc\n'; }
@test "empty-file" { check a b '' 0 ''; }
@test "delete" { check - '' 'a-b-c\n' 2 'abc\n'; }
@test "whole-file" { check abc '' 'abc' 1 ''; }
@test "new-contains-old" { check a aa 'a a\n' 2 'aa aa\n'; }
@test "overlapping" { check aa b 'aaa\n' 1 'ba\n'; }
@test "adjacent" { check aa b 'aaaa\n' 2 'bb\n'; }
@test "special-chars" { check 1.5 '\&$1 $& [x]' '1.5 and 125\n' 1 '\\&$1 $& [x] and 125\n'; }
@test "glob-chars" { check '*.txt' '?' 'a.txt *.txt\n' 1 'a.txt ?\n'; }
@test "across-lines" { check $'end\nstart' 'end start' 'end\nstart\n' 1 'end start\n'; }
@test "lf-to-crlf" { check $'\n' $'\r\n' 'a\nb\n' 2 'a\r\nb\r\n'; }
@test "crlf" { check a c 'a\r\nb\r\n' 1 'c\r\nb\r\n'; }
@test "no-final-newline" { check b c 'a b' 1 'a c'; }
@test "non-ascii" { check $'\xc3\xa9' e 'caf\xc3\xa9, cafe\n' 1 'cafe, cafe\n'; }
@test "case-sensitive" { check hello bye 'Hello hello\n' 1 'Hello bye\n'; }
@test "rosetta" {
printf 'Goodbye London!\n' >"$dir/a.txt"
printf 'Goodbye London! Goodbye London!\nGoodbye\n' >"$dir/b.txt"
[ "$(replace_in_files 'Goodbye London!' 'Hello New York!' "$dir/a.txt" "$dir/b.txt")" = "$(printf '1\n2')" ]
same "$dir/a.txt" 'Hello New York!\n'
same "$dir/b.txt" 'Hello New York! Hello New York!\nGoodbye\n'
}
@test "some-files-match" {
printf 'cat\n' >"$dir/a.txt"
printf 'dog\ncat dog\n' >"$dir/b.txt"
[ "$(replace_in_files dog fox "$dir/a.txt" "$dir/b.txt")" = "$(printf '0\n2')" ]
same "$dir/a.txt" 'cat\n'
same "$dir/b.txt" 'fox\ncat fox\n'
[ "$(ls -A "$dir" | wc -l | tr -d ' ')" = 2 ]
}
@test "no-files" {
[ "$(replace_in_files a b)" = "" ]
}
@test "many-lines" {
awk 'BEGIN { for (i = 0; i < 100000; i++) print "line " i }' >"$file"
[ "$(replace_in_files 'line ' L "$file")" = 100000 ]
[ "$(awk 'BEGIN { for (i = 0; i < 100000; i++) print "L" i }' | cksum)" = "$(cksum <"$file")" ]
}
@test "keeps-the-permissions" {
printf 'a\n' >"$file"
chmod 640 "$file"
[ "$(replace_in_files a b "$file")" = 1 ]
[ "$(ls -l "$file" | cut -c1-10)" = "-rw-r-----" ]
}
@test "not-found" {
run replace_in_files a b "$dir/missing.txt"
[ "$status" -eq 2 ]
}
@test "empty-old" {
printf 'a\n' >"$file"
run replace_in_files '' b "$file"
[ "$status" -eq 2 ]
same "$file" 'a\n'
}
@test "stop" {
printf 'a\n' >"$dir/a.txt"
printf 'a\n' >"$dir/c.txt"
run replace_in_files a b "$dir/a.txt" "$dir/missing.txt" "$dir/c.txt"
[ "$status" -eq 2 ]
same "$dir/a.txt" 'b\n'
same "$dir/c.txt" 'a\n'
}
References
- Rosetta Code, Globally replace text in several files (task text, from acmeism/RosettaCodeData), task text
- The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), rename, renameat, DESCRIPTION
- The Python Standard Library, Built-in Types, bytes.count; bytes.replace
- The Python Standard Library, os, os.replace
- Node.js documentation, Buffer, buf.indexOf
- Node.js documentation, File system, File system flags; fs.renameSync
- Java SE 25 API, java.nio.file.Files, createTempFile; move (ATOMIC_MOVE)
- .NET API reference, MemoryExtensions.IndexOf, IndexOf<T>(ReadOnlySpan<T>, ReadOnlySpan<T>)
- .NET API reference, File.Move, Move(String, String, Boolean)
- Go standard library, package bytes, Count; ReplaceAll
- Go standard library, package os, CreateTemp; File.Sync; Rename
- The Rust Standard Library, std::fs::rename, Description
- cppreference.com, std::basic_string::find, Description
- The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), awk, OPERANDS (assignment); Variables and Special Variables (ENVIRON); String Functions (index)
- The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), sed, Regular Expressions in sed; Editing Commands in sed (s)
- MDN Web Docs, String.prototype.replace(), Specifying a string as the replacement
- MDN Web Docs, String.prototype.replaceAll(), Parameters
- The Python Standard Library, re, re.sub
- GNU Bash Reference Manual, 3.5.3 Shell Parameter Expansion; 4.3.2 The Shopt Builtin (patsub_replacement)
- The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), xargs, DESCRIPTION; OPTIONS (-0)
- The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), find, OPERANDS (-exec, -print0)
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (bash) | I0 not checked yet |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag G9C785 Edit this page History Report an error Markdown