18.26 Replace Regexp in a File


We can replace strings within a line that match a regular expression using perl. For example, to replace strings that are at the beginning of a line that contain two asterisks, then an 8 digit date, then two more asterisks and a space, with an inline call to an R function in a bookdown document:

$ perl -pi.bak -e 's|^\*\*(\d{8})\*\* |`r#cite_date($1)` |' chapt1.Rmd
$ meld chapt1.Rmd.bak chap1.Rmd

In this example -i is used to do the replacement in place and .bak is added so that the original file kept as a backup in case anything should go wrong. We can use meld to compare the files to confirm all works as expected.

Once we are comfortable and have tested the process, we can repeat this for all Rmd files int eh current directory:

$ perl -pi.bak -e 's|^\*\*(\d{8})\*\* |`r#cite_date($1)` |' *.Rmd

Your donation will support ongoing availability and give you access to the PDF version of this book. Desktop Survival Guides include Data Science, GNU/Linux, and MLHub. Books available on Amazon include Data Mining with Rattle and Essentials of Data Science. Popular open source software includes rattle, wajig, and mlhub. Hosted by Togaware, a pioneer of free and open source software since 1984. Copyright © 1995-2022 Graham.Williams@togaware.com Creative Commons Attribution-ShareAlike 4.0