Tuesday, December 13, 2016

Recursively search for text in R scripts.

Often I find myself needing to search for .R or or .Rmd files in which I have used a specific function. There are a variety of searches that you can do; however, I wanted something that would work recursively at the command line of a Linux or Mac terminal. I found the answer here and have modified it a bit so that it works as a function in Bash (in this example I search through .R and . Rmd files).

Add the following to your ~/.bash_aliases file and then source ~/.bashrc:


findinRfun() {

if [ -z "$1" ]
 then
    echo "No argument supplied"
 else
    #search text is passed as argument $1
    find . -type f \( -name "*.R" -o -name "*.Rmd" -o -name "*.r" -o -name "*.rmd" \) -print0 | xargs --null grep --with-filename --line-number --no-messages --color --ignore-case "$1"
fi
            }

alias findinR=findinRfun


Now, at the command line, you can search through all the files below the current location that contain your search text.

findinR mysearchtext