Reputation: 8567
In the example below, I generate the bibliography for packages from a chunk of code. However, there is an error in the BibTeX entry for one package. I could modify this entry manually but my change will be overwritten next time I knit my file.
Therefore, I would like to know if it is possible to modify the line in the .bib file from a chunk in R Markdown, so that the entry is automatically corrected each time the file is knitted.
Example:
---
title: "Cite R packages"
author: ''
date: ""
output:
pdf_document
bibliography: mistakeref.bib
---
```{r echo=FALSE}
# If not installed yet:
# install.packages("cem")
```
This is a citation of a paper: @R-cem
```{r cite-packages, echo=FALSE}
knitr::write_bib("cem", file = "mistakeref.bib", tweak = TRUE)
```
mistakeref.bib
will be created by the code, but there is an error in the Bibtex entry for the package cem
. I would like to replace:
author = {{Iacus} and Stefano M. and {King} and {Gary} and {Porro} and {Giuseppe}},
by:
author = {Stefano M. Iacus and Gary King and Giuseppe Porro},
Basically, it would be a sort of automatic "search and replace" from R. I have some trouble understanding this answer and I am not sure if it corresponds to what I would like to do.
Upvotes: 1
Views: 415
Reputation: 73612
Read in the .bib file using readLines
. Then use grep
to identify the "bad" line (.
is a special character, so we need to escape using \\.
). Then just replace and save using cat
.
l <- readLines("mybib.bib")
l[grep("Stefano M\\.", l)] <-
" author = {Stefano M. Iacus and Gary King and Giuseppe Porro},"
cat(l, sep="\n", file="mybib1.bib")
Just extend the grep
regex until there is one single match.
Upvotes: 1