A post-processing helper that performs find-and-replace directly on a
rendered .rtf file's bytes. It is meant for the "last mile" of TLG
production – small textual fixes to a finished deliverable – not as a
substitute for building the report correctly with the pipe API.
Usage
rtf_replace_text(
input_file,
target,
replacement,
output_file = NULL,
encoding = "UTF-8",
use_regex = FALSE,
case_insensitive = FALSE,
backup = TRUE
)Arguments
- input_file
Path to the RTF file to read.
- target
Character vector of strings (or regex patterns when
use_regex = TRUE) to search for. Must be non-empty.- replacement
Character vector of replacements. Either the same length as
target, or length 1 (recycled to every target).- output_file
Path to write the result to.
NULL(default) overwritesinput_filein place (seebackup).- encoding
Encoding of
input_file, used when reading and writing. Default"UTF-8". rtfreporter writes ASCII-safe RTF, so the default is usually correct.- use_regex
Logical.
FALSE(default) treatstargetas a fixed string;TRUEtreats it as a Perl-compatible regular expression.- case_insensitive
Logical.
FALSE(default) matches case-sensitively. WhenTRUE, matching ignores case (fixed targets are safely escaped before the case-insensitive match, so regex metacharacters stay literal).- backup
Logical. When overwriting in place (
output_file = NULL), first copy the original topaste0(input_file, ".bak"). DefaultTRUE. Ignored whenoutput_fileis given.
Details
One or more target strings are replaced by replacement. Pass equal-length
vectors to apply several replacements, or a single replacement to use the
same value for every target. Replacements are applied sequentially, so
an earlier replacement can affect a later one.
Important – this operates on the raw RTF bytes
The file is treated as plain text, so a target only matches when it appears
literally in the file. RTF stores formatting as control words and
escapes non-ASCII characters (\\uN, \\'XX), so:
Plain ASCII runs and RTF control words match and replace fine.
Text that is split across RTF control words, or non-ASCII characters that the renderer escaped, will not match their on-screen form.
For anything structural, change the inputs to the pipe API instead.
Examples
doc <- rtf_document() |>
rtf_tables(data.frame(Parameter = "Age", Value = "75.1")) |>
rtf_titles(list(c("Table 14.1.1 DRAFT vX.Y", "Saftey Population")))
f <- tempfile(fileext = ".rtf")
generate_rtfreport(doc, f, overwrite = TRUE)
# Fix a footnote wording in place (keeps a .bak copy)
rtf_replace_text(f, "Saftey Population", "Safety Population")
# Several replacements at once, writing to a new file
rtf_replace_text(
f,
target = c("DRAFT", "vX.Y"),
replacement = c("FINAL", "v1.0"),
output_file = tempfile(fileext = ".rtf")
)