Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing the nth number in a string

Tags:

regex

r

I have a set of files which I had named incorrectly. The file name is as follows.

Generation_Flux_0_Model_200.txt
Generation_Flux_101_Model_43.txt
Generation_Flux_11_Model_3.txt

I need to replace the second number (the model number) by adding 1 to the existing number. So the correct names would be

Generation_Flux_0_Model_201.txt
Generation_Flux_101_Model_44.txt
Generation_Flux_11_Model_4.txt

This is the code I wrote. I would like to know how to specify the position of the number (replace second number in the string with the new number)?

reNameModelNumber <- function(modelName){

  #get the current model number
  modelNumber = as.numeric(unlist(str_extract_all(modelName, "\\d+"))[2])

  #increment it by 1
  newModelNumber = modelNumber + 1

  #building the new name with gsub 
  newModelName = gsub("  regex ", newModelNumber, modelName) 

  #rename
  file.rename(modelName, newModelName)


}


reactionModels = list.files(pattern = "^Generation_Flux_\\d+_Model_\\d+.txt$")

sapply(reactionFiles, function(x) reNameModelNumber(x))
like image 559
SriniShine Avatar asked May 05 '18 09:05

SriniShine


1 Answers

We can use gsubfn to incremement by 1. Capture the digits ((\\d+)) followed by a . and 'txt' at the end ($`) of the string, and replace it by adding 1 to it

library(gsubfn)
gsubfn("(\\d+)\\.txt$", ~ as.numeric(x) + 1, str1)
#[1] "Generation_Flux_0_Model_201"  "Generation_Flux_101_Model_44"
#[3] "Generation_Flux_11_Model_4"  

data

str1 <- c("Generation_Flux_0_Model_200.txt", "Generation_Flux_101_Model_43.txt", 
                   "Generation_Flux_11_Model_3.txt")
like image 196
akrun Avatar answered Oct 11 '22 14:10

akrun