ivo
ivo

Reputation: 77

Replace first characters of file names

I tried to replace the first 3 characters of 11 files with a common letter

x <- list.files(pattern = ".txt", )
file.rename(substring(x, 1,3), paste0("R_",1:11))
[1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE

What am I doing wrong here?

Upvotes: 1

Views: 981

Answers (1)

user3357177
user3357177

Reputation: 385

Here is one way using gsub and a regular expression:

x <- list.files(pattern = ".txt")
x2 <- gsub('^.{3}', 'R_', x) # substitute first 3 characters with 'R_'
file.rename(x, x2)

Learning regex is one of the most useful skills for manipulating files in R

Upvotes: 2

Related Questions