Skip to content

Instantly share code, notes, and snippets.

@mages
Created December 31, 2011 13:30
Show Gist options
  • Star 18 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save mages/1544009 to your computer and use it in GitHub Desktop.
Save mages/1544009 to your computer and use it in GitHub Desktop.
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")
}
@carrollrm
Copy link

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