Skip to contents

replace_in_file() searches each line of a file and replaces a specific pattern when found.

Usage

replace_in_file(file, pattern, replacement)

Arguments

file

A character vector specifying the path(s) to the file(s) in which to perform the replacement.

pattern

A character vector specifying the pattern(s) (regular expressions) to search for. If multiple patterns are provided, each must correspond to a replacement of the same length.

replacement

A character vector specifying the replacement value(s) to use. Each element is applied to the corresponding pattern via str_replace_all().

Value

An invisible NULL. This function is used for its side effect.

Examples

file <- tempfile()
file.create(file)
#> [1] TRUE

con <- file(file, "r+")
data <- c("01:00:56", "", "Test", "")
writeLines(data, con = con)
close(con)

replace_in_file(
  file = file,
  pattern = "([0-1][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]",
  replacement = ""
)

con <- file(file, "r+")
readLines(con)
#> [1] ""     ""     "Test" ""    
close(con)