Create a gist now

Instantly share code, notes, and snippets.

Embed
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

This comment has been minimized.

Show comment
Hide comment
@EconometricsBySimulation

EconometricsBySimulation Jul 29, 2014

Thanks! Very helpful!

Thanks! Very helpful!

@ashgillman

This comment has been minimized.

Show comment
Hide comment
@ashgillman

ashgillman Oct 14, 2014

Thanks

Thanks

@MatthewSchumwinger

This comment has been minimized.

Show comment
Hide comment
@MatthewSchumwinger

MatthewSchumwinger 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 "/"

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

@jlcho

This comment has been minimized.

Show comment
Hide comment
@jlcho

jlcho Jul 23, 2015

Awesome. This was helpful. :)

jlcho commented Jul 23, 2015

Awesome. This was helpful. :)

@Shansh

This comment has been minimized.

Show comment
Hide comment
@Shansh

Shansh 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 :)

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

This comment has been minimized.

Show comment
Hide comment
@MarcinKosinski

MarcinKosinski Jun 21, 2016

So simple.... Thank you!

So simple.... Thank you!

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