Use grep to find text in a note
Search for specific patterns in your files
Lab notebooks are great for capturing your actions and reflections in a timestamped manner, but who remembers the date when you did that thing that you want to do again today? To find a note from about a month ago, when I compared the bowtie2 and bwa aligners, I can search for the two terms using grep.
Move into the folder you want to search. My folder is called ‘notes’.
cd notes/
Search this folder .
for files with the suffix .md
. Print the output and pipe them as arguments to grep. As the grep man pages say, grep searches the named input files for lines containing a match to the given pattern. In the case below, the pattern is bowtie2
.
find . -name '*.md' -print | xargs grep 'bowtie2'
By default, find
looks in the directory you are currently in, so you don’t need the .
. Also, by default, find
prints the names of the directories and files inside them, so you don’t need -print
. If you don’t want to specify a file extension and do want to look in all files, then you don’t need -name
.
You can look for the presence of multiple words in a file with the following:
find | xargs grep -e 'bowtie2' -e 'bwa'
grep
grep 'pattern'
- grep stands for ‘gnu regular expressions’
- grep searches input files for matches to the argument pattern (in quotes)
- in the case above, the pattern is ‘bowtie2’
grep 'bowtie[^2]'
- returns all files that have the word ‘bowtie’, but not
^
those that have ‘bowtie2' - the not
^
symbol applies to all letters within the brackets - e.g. you could write
[^234]
so file names with 2, 3, or 4 after ‘bowtie’ would NOT be returned - grep is not “hungry”, meaning not all of the characters in the strings it reviews have be accounted for in the string it is searching for
- when grep finds a match in a line, it copies the line to standard output
mv
cannot process the output of grep, thus xargs is used above
grep --version
- grep comes with OSX command line utilities
- more updated versions of grep can be installed with Homebrew (not necessary):
brew install grep