Created
December 31, 2011 13:30
-
-
Save mages/1544009 to your computer and use it in GitHub Desktop.
Search and replace string across files with R
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## 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") | |
} |
Thanks
Fantastic. I used this as a basis to build a helper function that changes file paths from PC environment "" to Mac environment "/"
Awesome. This was helpful. :)
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 :)
So simple.... Thank you!
Thanks you !
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.
That is very cool! Thanks for sharing!
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
Thanks! Very helpful!