Search code examples
runzip

Unzip and rename files keeping original file extension


I want to unzip the files inside a folder and rename them with the same name as their .zip file of origin BUT keeping the original extension of the individual files. Any ideas on how to do this?

Reproducible example:

# Download zip files
  ftppath1 <- "ftp://geoftp.ibge.gov.br/malhas_digitais/censo_2010/setores_censitarios/se/se_setores_censitarios.zip"
  ftppath2 <- "ftp://geoftp.ibge.gov.br/malhas_digitais/censo_2010/setores_censitarios/al/al_setores_censitarios.zip"
  download.file(ftppath1, "SE.zip", mode="wb") 
  download.file(ftppath2, "AL.zip", mode="wb") 

What I had in mind was something as naive as this:

# unzip and rename files
  unzip("SE.zip", file_name= paste0("SE",.originalextension))
  unzip("AL.zip", file_name= paste0("AL",.originalextension))

In the end, these are the files I would have in my folder:

SE.zip
AL.zip

AL.shx
AL.shp
AL.prj
AL.dbf

SE.shx
SE.shp
SE.prj
SE.dbf

Solution

  • for (stem in c('SE','AL')) {
        zf <- paste0(stem,'.zip'); ## derive zip file name
        unzip(zf); ## extract all compressed files
        files <- unzip(zf,list=T)$Name; ## get their orig names
        for (file in files) file.rename(file,paste0(stem,'.',sub('.*\\.','',file))); ## rename
    };
    system('ls;');
    ## AL.dbf  AL.prj  AL.shp  AL.shx  AL.zip  SE.dbf  SE.prj  SE.shp  SE.shx  SE.zip