Skip to content

Instantly share code, notes, and snippets.

@daijiang
Last active May 19, 2016 15:29
Show Gist options
  • Save daijiang/50a82ae1489a41ca116017b497c207f3 to your computer and use it in GitHub Desktop.
Save daijiang/50a82ae1489a41ca116017b497c207f3 to your computer and use it in GitHub Desktop.
Get citation keys from tex file; then get a subset of cited items as a bib file.
library(stringr)
library(RefManageR)
## to get citation keys (with forms: author2016title) from tex file
get_cite_key = function(tex){
text = readLines(tex)
# \cite*{}
key_1 = str_replace_all(grep("^.*cite[a-z]{0,7}\\{([A-Za-z0-9,-]*)\\}.*$",
x = text, value = T),
pattern = "^.*cite[a-z]{0,7}\\{([A-Za-z0-9,-]*)\\}.*$",
replacement = "\\1")
key_1 = sort(unique(unlist(strsplit(unique(key_1), ","), recursive = T)))
# \citep[][]{}
key_2 = str_replace_all(grep("^.*cite[a-z]{0,7}\\[.*\\]\\{([A-Za-z0-9,-]*)\\}.*$",
x = text, value = T),
pattern = "^.*cite[a-z]{0,7}\\[.*\\]\\{([A-Za-z0-9,-]*)\\}.*$",
replacement = "\\1")
key_2 = sort(unique(unlist(strsplit(unique(key_2), ","), recursive = T)))
sort(unique(c(key_1, key_2)))
}
key0 = get_cite_key(tex = "chapter1/chapter1.tex")
# to extract cited items from a bigger bib file
bib1 = ReadBib("chapter1/larger.bib", check = T)
# to save cited items
WriteBib(bib1[[key0]], "chapter1/ch1.bib", biblatex=F)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment