Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Search and replace string across files with R
## The following example demonstrates
## how a serach and replace string task
## can be peformed with R across several files
## Create two text files with content
filenames <- c( tempfile(), tempfile() )
for( f in filenames ){
cat("We wish you a Merry Christmas!\n\nBest regards\n", file=f)
}
## Replace Merry Christmas with Happy New Year
for( f in filenames ){
x <- readLines(f)
y <- gsub( "Merry Christmas", "Happy New Year", x )
cat(y, file=f, sep="\n")
}
## Review output
for( f in filenames ){
cat(readLines(f), sep="\n")
}
@EconometricsBySimulation

Thanks! Very helpful!

@ashgillman
Copy link

ashgillman commented Oct 14, 2014

Thanks

@MatthewSchumwinger
Copy link

MatthewSchumwinger commented Oct 28, 2014

Fantastic. I used this as a basis to build a helper function that changes file paths from PC environment "" to Mac environment "/"

@jlcho
Copy link

jlcho commented Jul 23, 2015

Awesome. This was helpful. :)

@Shansh
Copy link

Shansh commented Mar 24, 2016

Impressive! Thank you very much. You spared me a lot of time. The web-site that I admin, recently has moved from .org to .com. I have used your loop for replacing and it worked perfectly :)

@MarcinKosinski
Copy link

MarcinKosinski commented Jun 21, 2016

So simple.... Thank you!

@r0bis
Copy link

r0bis commented Jan 17, 2019

Thanks you !

@GutoBarros
Copy link

GutoBarros commented Jan 20, 2019

Thank you soooo much!
I've been struggling with that for a long time and your kindness in sharing saved me a lot of work.

@Seneketh
Copy link

Seneketh commented Jul 5, 2019

That is very cool! Thanks for sharing!

@carrollrm
Copy link

carrollrm commented Jul 19, 2019

Yesss! This is exactly what I needed!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment