Create BASH aliases to make searching through code easier

I am one of those people who frequently consults my previous code for working examples when writing new code. The basic tool for doing this is grep. For example, if you have a bunch of code in say /home/me/code and want to find an example of DecimalFormat, you could do something like:

grep -r DecimalFormat /home/me/code |less

But the thing is, for my classes I’m taking I tend to have code mixed with a lot of other files. When I grep recursively through the directories I generally don’t want to match with files that are not code. I only want to search through .java source code files.

You can do a more advanced grep such as this:

grep -r --include "*.java" DecimalFormat /home/me/edu/java_course/

But this is a lot of typing. It would be nice if you could just have one succinct command that would do everything, and all you have to do is supply as an argument the string you are searching for. For example:

jgrep DecimalFormat

This is actually really easy to do with a BASH function. Here’s how:

Put something like the code below in your ~/.bashrc In this example I added an option for color and the output is piped to the less command so that it can be easily scrolled:

jgrep_func ()
{
grep -r --color=always --include "*.java" "$@" ~/edu/java_course/ |less;
}

alias jgrep='jgrep_func'

Here’s another example for SQL code:

sqgrep_func ()
{
grep -r --color=always --include "*.sql" "$@" ~/edu/sql_course/ |less;
}

alias sqgrep='sqgrep_func'

Remember to source your .bashrc:

. ~/.bashrc

Now you’re good to go.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *