Home > OS >  Using a gsub to insert a word rather than replace a word
Using a gsub to insert a word rather than replace a word

Time:01-27

I have the following file path to which i want to rename. The current path (for an example) is Downloads/strip/2022.dat and i wish to change this to Downloads/strip/old/2022.dat. I've tried gsubbing like this;

aa = Downloads/strip/2022.dat
aa = gsub("\\/strip/. ", "/Old/", aa)

where im trying to say keep everything with the , and add "old after the strip/ but this still seems to remove the strip/. I've also tried .^ and .$ but no luck.

CodePudding user response:

Generally, we can try the following approach with sub():

x <- "Downloads/strip/2022.dat"
output <- sub("([^/] )$", "old/\\1", x)
output

[1] "Downloads/strip/old/2022.dat"

CodePudding user response:

You can do it more simply by replacing 'strip', with 'strip/old'. No regex required:

aa ='Downloads/strip/2022.dat' 
gsub("strip", "strip/old", aa, fixed = TRUE)
[1] "Downloads/strip/old/2022.dat"
  • Related