简体   繁体   中英

R Find and replace multiple scripts at once

I have several R scripts and my client just wants to change the colours of the graphs.

Is there any way to find and replace all at once instead of find&replace opening the scripts one by one?

I have tried a little tool called fnr with .txt files and it works, but it doesn't with .R files.

Here's an approach using R, where you create a function that finds-and-replaces text in a file and you apply this function to all of the R scripts in your directory.

In the example below, this changes the code color = 'green' in any R script to color = 'blue' .

# Define function to find-and-replace text in a single file
  file_find_replace <- function(filepath, pattern, replacement) {
    file_contents <- readLines(filepath)
    updated_contents <- gsub(x = file_contents, pattern = pattern, replacement = replacement)
    cat(updated_contents, file = filepath, sep = "\n")
  }

# Apply the function to each of the R scripts in the directory
  my_r_scripts <- list.files(path = my_dir, pattern = "(r|R)$")

  for (r_script in my_r_scripts ) {
    file_find_replace(r_script,
                      "color = 'green'",
                      "color = 'blue'")
  }

I found a very useful tool called grepWin. It has plenty of options for search and replace. It search subfolders, different types of matches, date filters, etc...

You can download it at https://tools.stefankueng.com/grepWin.html

在此处输入图片说明

There's also regexxer: https://github.com/GNOME/regexxer for Linux. RStudio developers seem to be working on a solution also, as documented here (which contains information on a few other approaches): https://github.com/rstudio/rstudio/issues/2066

The xfun R package has a few functions to do exactly this ( gsub_file() , gsub_dir() , etc.)

For example, if all your R scripts are in a sub-folder in your working directory, you can simply write:

library(xfun)

gsub_dir(dir = "Scripts", pattern = "color = 'green'", replacement = "color = 'blue'")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM