I have a folder that contains about 140 .tif files. I need to remove the '[]' from the end of each file name.
For example, I have a file named "GOGA_na_MP_FortBakerTopography_196[].tif" and need it to be renamed to "GOGA_na_MP_FortBakerTopography_196.tif".
I have tried the following using a for loop to iterate through all files and gsub to remove the brackets in replace of nothing.
raster_files <- list.files(pattern =".tif$", full.names = TRUE)
for (files in raster_files){
raster_name <- basename(files)
file_name <- gsub("[", "", gsub("]", "", raster_name, fixed = TRUE), fixed = TRUE)
}
I have read through all the other stack questions that are similar to this (inlcuding Removing brackets) and tried to implement their solutions and have had no success. Any help is greatly appreciated thank you.
EDIT EDIT PART 2
Thank you for support on this. I am new to this and I appreciate the patience.
I have figured the code out and have it working when I print out the file names. However, I cannot seem to figure out how to overwrite the name of the files within my FileExplorer and not just within RStudio. The files in the explorer are not renamed but they show up correctly when printed to the console in R.
Example code:
raster_files <- list.files(pattern =".tif$", full.names = TRUE)
file_name = character(length(raster_files))
file_name
for (i in seq_along(raster_files)){
raster_names <- basename(raster_files[i])
file_name[i] <- gsub("[]", "", raster_names, fixed = TRUE)
print(file_name[i])
}
Your
gsubcode is fine (could be improved, but it should work). The issue is your loop. You are overwritingfile_nameat every iteration. You could fix your loop like this:Note how we use
file_name[i]above, so that we're assigning to a different element offile_nameat each loop iteration.However, the functions
basenameandgsubare vectorized so looping just makes your code more complicated and less efficient. We can use the vectorization to work on the whoraster_filesvector at once:But we can do better still -
gsubisn't limited to one bracket at a time: