89_Simple
89_Simple

Reputation: 3805

Renaming multiple files in folder

  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"

Upvotes: 1

Views: 61

Answers (3)

nghauran
nghauran

Reputation: 6768

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()))

Upvotes: 3

akrun
akrun

Reputation: 886948

We can use str_remove

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

Upvotes: 2

acylam
acylam

Reputation: 18661

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"

Upvotes: 2

Related Questions