Search code examples
rrenamefile-rename

Renaming multiple files while keeping a part of original file name


I have various files with following nomenclature:

c_gls_ALDH-AL-DH-BB_200602030000_CUSTOM_VGT_V1.4.1

c_gls_ALDH-AL-DH-BB_200602130000_CUSTOM_VGT_V1.4.1

c_gls_ALDH-AL-DH-BB_200602210000_CUSTOM_VGT_V1.4.1

c_gls_ALDH-AL-DH-BB_200603030000_CUSTOM_VGT_V1.4.1

The numeric in middle of file name represents year, month, date. I want to rename all the files at once while keeping only the dates i.e., '200602030000' for each file and want to remove 'c_gls_ALDH-AL-DH-BB_' and '_CUSTOM_VGT_V1.4.1' from the file names.

I am able to do it for single file using following code:

fromfile <- c('c_gls_ALDH-AL-DH-BB_200601130000_CUSTOM_VGT_V1.4.1.tiff')
tofile <- c('200601130000.tiff')
file.rename(fromfile, tofile)

But I am not able to do it for all the files together. I am doing it in R.


Solution

  • file.rename is vectorized so:

    fromfile <- c("c_gls_ALDH-AL-DH-BB_200602030000_CUSTOM_VGT_V1.4.1.tiff",
      "c_gls_ALDH-AL-DH-BB_200602130000_CUSTOM_VGT_V1.4.1.tiff",
      "c_gls_ALDH-AL-DH-BB_200602210000_CUSTOM_VGT_V1.4.1.tiff",
      "c_gls_ALDH-AL-DH-BB_200603030000_CUSTOM_VGT_V1.4.1.tiff")
    
    tofile <- sub(".*_(\\d+)_.*", "\\1.tiff", fromfile)
    file.rename(fromfile, tofile)