This code will answer your first question albeit with a small change in logic.
Firstly, lets create a backup of all the csv
containing []
by copying them to another folder. For eg - If your csv
s were in directory "/Users/xxxx/Desktop/Sub"
, we will copy them in the folder Backup
.
Therefore,
library(stringr)
library(tools)
setwd("/Users/xxxx/Desktop/Sub")
dir.create("Backup")
files<-data.frame(file=list.files(path=".", pattern = "*.csv"))
for (f in files)
file.copy(from= file.path("/Users/xxxx/Desktop/Sub", files$file), to= "/Users/xxxx/Desktop/Sub/Backup")
This has now copied all the csv files to folder Backup.
Now lets rename the files in your original working directory by removing the "[]".
I have taken a slightly longer route by creating a dataframe with the old names and new names to make things easier for you.
Name<-file_path_sans_ext(files$file)
files<-cbind(files, Name)
files$Name<-gsub("\\[", "",files$Name)
files$Name<-gsub("\\]", "_",files$Name)
files$Name<-paste(files$Name,".csv",sep="")
This dataframe looks like:
files
file Name
1 [Residential]20150928_0000_4.csv Residential_20150928_0000_4.csv
2 [Residential]20151001_0000_1.csv Residential_20151001_0000_1.csv
3 [Residential]20151101_0000_3.csv Residential_20151101_0000_3.csv
4 [Residential]20151121_0000_2.csv Residential_20151121_0000_2.csv
5 [Residential]20151231_0000_5.csv Residential_20151231_0000_5.csv
Now lets rename the files to remove the "[]". The idea here is to replace file with Name:
for ( f in files$file)
file.rename(from=file.path("/Users/xxxx/Desktop/Sub", files$file),
to=file.path("/Users/xxxx/Desktop/Sub",files$Name))
You've renamed your files now. If you run: list.files(path=".", pattern = "*.csv")
You will get the new files:
"Residential_20150928_0000_4.csv"
"Residential_20151001_0000_1.csv"
"Residential_20151101_0000_3.csv"
"Residential_20151121_0000_2.csv"
"Residential_20151231_0000_5.csv"
Try it!