1
votes
  list.files()

  "file_iteration1_2019-03-01-03-38-16.csv"
  "file_iteration1_obs_2019-03-01-03-38-16.csv" 
  "file_iteration1_modp_2019-03-01-03-38-16.csv"

I want to rename these files without the year and time stamp so it looks like

"file_iteration1.csv"
"file_iteration1_obs.csv" 
"file_iteration1_modp.csv"
3

3 Answers

3
votes

Since you want to rename the files in folder, you can combine file.rename() and gsub() (sub() or stringr::str_remove(), suggested by @avid_useR and @akrun, would also work fine). Try out:

file.rename(list.files(), gsub('_[0-9-]+', '', list.files()))
2
votes

With sub:

x <- c("file_iteration1_2019-03-01-03-38-16.csv", 
"file_iteration1_obs_2019-03-01-03-38-16.csv",
"file_iteration1_modp_2019-03-01-03-38-16.csv")

sub('_\\d{4}(-\\d{2}){5}', '', x)
# [1] "file_iteration1.csv"      "file_iteration1_obs.csv"  "file_iteration1_modp.csv"
2
votes

We can use str_remove

library(stringr)
str_remove(files, "_[0-9-]+")
#[1] "file_iteration1.csv"      "file_iteration1_obs.csv"  "file_iteration1_modp.csv"