Home > OS >  Find and/or replace not at comment lines
Find and/or replace not at comment lines

Time:09-23

I am using Rstudio 1.4.1106, and we all know that we can use Ctrl F to find or replace. Typically, Rstudio will find/replace in any line of code, including the comment lines (lines starting with #). I would like to find/replace only in (actual) command lines (commands that actually doing something, even that line may have # at the end for comment).

Do you have any solution?

CodePudding user response:

You can just write a R function which modifies the file only in non comment areas:

library(tidyverse)

file_replace <- function(file, ...) {
  file %>%
    read_lines() %>%
    map_chr(function(l) {
      if(l %>% str_starts("#")) {
        # comment 
        l
      } else {
        # code
        parts <- l %>% str_split("#") %>% simplify()
        
        if(length(parts) == 2) {
          # code line contains comment
          paste0(
            parts[[1]] %>% str_replace_all(...),
            "#",
            parts[[2]]
          )
        } else {
          l %>% str_replace_all(...)
        }
      }
    }) %>%
    write_lines(file)
}

Input file foo.R:

#' foo
#' @param foo: number to increase
f <- function(foo) {
  foo   1 # increasing the foo
}

Do the replacement:

file_replace("foo.R", pattern = "f[o]{2}", replacement = "bar")

Output file foo.R after replacement:

#' foo
#' @param foo: number to increase
f <- function(bar) {
  bar   1 # increasing the foo
}

This example also illustrate the danger in this method: By doing so, you do not update doc-strings which are part of the comments!

CodePudding user response:

You can use a regex to find, and ignore lines that start with a comment symbol. For example, you can put (?<!#.*)\bsearchString\b to ignore matching content from lines that start with a #.

This is basically doing a negative lookbehind for # to ensure that it doesn't match searchString that has a # before it, the quantifier in the lookbehind ensure that we exclude things like # some things searchString. This isn't very ideal for a regex and may not work in some languages that don't allow non-fixed width inside lookbehinds, but it works in the find and replace regex in rstudio so should serve OP's purpose. Let me know if there are any edge cases this regex is missing.

Don't forget to tick the regex box before trying out!

  • Related