Skip to content

Instantly share code, notes, and snippets.

@stevekm
Last active September 28, 2015 16:09
Find my .Rnw files and search their contents for a string, using find and grep. There is probably a more elegant way to do this, but this one works.
#!/bin/bash
# look in my /Users/ dir
# look for the .Rnw files
# suppress the permission denied messages with this:
# 2> /dev/null
# these are the files to search:
FILES=$(find /Users/username -type f -name "*.Rnw" 2> /dev/null)
# this is the pattern I want to find within the files
PATTERN="Bedtools"
for i in $FILES; do
# if the file contains the search string, print the file name
if [[ -n $(grep -F $PATTERN $i) ]] ; then
# grep; -F fixed pattern, -l ouput file name of matches
# [[ -n ]]; test (see man test), -n nonzero string length
# grep searches file for our pattern
# and outputs filenames if found
# [[ -n ]] tests to see if this output is nonzero length
# on a successful search, grep will print the file name
grep -Fl $PATTERN $i
# or echo $i
fi ;
done
# this will break with file pathes or names that include spaces
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment