Rename files in R - delete character

Viewed 106

I have multiple files to analyze that are now called "E - 04(fld 1 wv Red - Cy5)" ad I want to delete the 0 so that they become just "E - 4(fld 1 wv Red - Cy5)". Is there a way to do it?

Thanks!

4 Answers

Just to add to Rui Barradas answer, you could use the package stringr and remove the zero from the name or names, by typing:

fileNames <- "E - 04(fld 1 wv Red - Cy5)"
stringr::str_remove(fileNames, '0')
[1] "E - 4(fld 1 wv Red - Cy5)"

This base R regex seems to do the job.

x <- "E - 04(fld 1 wv Red - Cy5)"
sub("(^[^[:digit:]]*)0([[:digit:]]+.*$)", "\\1\\2", x)
#[1] "E - 4(fld 1 wv Red - Cy5)"

If you want to change many filenames, maybe a function will make it easier to perform the task.

changeName <- function(x){
  sub("(^[^[:digit:]]*)0([[:digit:]]+.*$)", "\\1\\2", x)
}

x <- "E - 04(fld 1 wv Red - Cy5)"
changeName(x)
#[1] "E - 4(fld 1 wv Red - Cy5)"

y <- c("E - 04(fld 1 wv Red - Cy5)", "E - 06789(fld 1 wv Red - Cy5)")
#[1] "E - 4(fld 1 wv Red - Cy5)"    "E - 6789(fld 1 wv Red - Cy5)"
changeName(y)

You can use look arounds and str_remove:

> library(stringr)
> s
[1] "E - 04(fld 1 wv Red - Cy5)"
> str_remove(s, '(?<=E - )0(?=4\\(fld 1 wv Red - Cy5\\))')
[1] "E - 4(fld 1 wv Red - Cy5)"
> 

We can also use sub

sub("0", "", str1)
#[1] "E - 4(fld 1 wv Red - Cy5)"

data

str1 <- "E - 04(fld 1 wv Red - Cy5)"
Related