Search code examples
rrenamebatch-rename

Trying to copy and move a record number from the middle of a file name to the front of a file name, word document, using RStudio


I am trying to take a folder of word documents and rename them, each has a species name, possible observation count, e.g. 2 of 10, country identifier, e.g. [C] for Cambodia, date that might be . seperated or not, a field record number, given by fr# before the number and brackets that might be ( , [ or {, with location name in text at the end. Example:

species name 2 of 10 [C] 27.Aug.12 [Fr#2046] location name.doc

I need to remove the fr# at add it onto the front of the file name, the original fr# can remain in the middle also, Example:

2046 species name 2 of 10 [C] 27.Aug.12 [Fr#2046] location name.doc

I've managed to remove the front of the name to show the number, but have struggled to do anything else.

library(stringr)            #install stingr from library
my_path <- "/Users/Documents/RStudio_Docs/Field _Record_Rename/"  # Define working directory
my_path                                   # Print path to working directory
file_names_old <- list.files(my_path)              # Get current file names
file_names_old                                     # Print current file names
sub(".*#", "",file_names_old)

Any help would be appreciated, thank you.


Solution

  • I would use stringr::str_extract to get the numbers preceded by "Fr#" and then paste them to the start of the file name:

    x = "species name 2 of 10 [C] 27.Aug.12 [Fr#2046] location name.doc"
    
    fr = str_extract(x, "(?<=Fr#)\\d+")
    x = paste(fr, x)
    x
    # [1] "2046 species name 2 of 10 [C] 27.Aug.12 [Fr#2046] location name.doc"