Skip to contents

[Maturing]

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

Usage

replace_in_file(dir = clipr::read_clip(), pattern, replacement)

Arguments

dir

(Optional) a string indicating the directory of the files. Defaults to clipboard content.

pattern

A string indicating the pattern to look for. The default interpretation is a regular expression. This parameter will be used on stringr::str_replace_all().

replacement

A string indicating the replacement value. This parameter will be used on stringr::str_replace_all().

Value

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

Examples

file_name <- tempfile(tmpdir = tempfile())
dir_name <- dirname(file_name)
dir.create(dir_name)
file.create(file_name)
#> [1] TRUE

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

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

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