Grep

Finding stuff in a codebase is generally as simple as:

[source]grep "term to search for" -r .[/source]

The -r means recursive input, and the . means the current directory

But there are standard things we can do to make the output better to digest:

Add Line numbers so it’s easier to get to the position in the target source file:

[source]grep "term to search for" -r -n .[/source]

Don’t search binary files as we’re generally only interested in text files:

[source]grep "term to search for" -r -n -I .[/source]

Ignore case if you’re not too sure about the case in a sentence (useful when you’re looking for printed text in a code base)

[source]grep "term to search for" -r -n -I -i .[/source]

Basic Regular Expressions

All the searches below use most of the options outlined above as a base for searching (or grepping!)

Some help from the grep man page:

?      The preceding item is optional and matched at most once.
*      The preceding item will be matched zero or more times.
+      The preceding item will be matched one or more times.
{n}    The preceding item is matched exactly n times.
{n,}   The preceding item is matched n or more times.
{n,m}  The preceding item is matched at least n	times, but not more than m times.

Search for a certain prefix with a range of postfix. This search matches the prefix exactly, and lets you control what the rest of the match contains.

NOTE: The in this search, even prefix will return as a result. The asterix at the end of the range of characters signifies that there *may* be any of the sequence after the prefix, but there might not be either.

[source]grep -P loca[a-zA-Z_]* -r -n -I -i .[/source]

The same, but force a suffix, so there *must* be something matched beyond the prefix. Use the + match instead of the period.

NOTE: These regular expressions do not work in the basic regular expression mode (The standard mode for GREP), and so we have to include the flag to tell grep these are Perl regular expressions. This is at least true of GREP on Windows.

[source]grep -P loca[a-zA-Z_]+ -r -n -I -i .[/source]

Leave a Reply