Creating a shortcut for find/grep

by  • September 6, 2011 • Uncategorized

I don’t know about you, but I find myself having to use find/grep constantly to find things on the servers I work on. And I get tired of typing long commands over and over again. If you feel the same, this article may help. Now, if you’re a bit new at linux or a little rusty on your command line chops, you may not know or remember how to use find and grep. Many people just use grep, but using find and grep together is faster and more effective. So if I wanted to find all the php files that have the word “content” in it. My favorite command for accomplishing this is like so:

find . -name '*.php' | xargs grep -s 'content'

What this means is, find all the files that end with the extension .php in the current directory and pipe the results into grep. Suppressing all errors (-s) look for the word “content” in every file and display the name of the file as well as the line of code that appears on.

If you’re anything like me, it took me awhile (years ago) to remember this command when I needed it. And now, I use it constantly, but frankly, I get tired of typing it. So, I figured out (not really being a “linux guy”) how to create an alias or shortcut for this command. Start by editing the .bashrc file in your root directory like so:

vi ~/.bashrc

Then add these lines of code to the bottom:

alias search="find . -name '*.php'|xargs grep -s "

alias searchjs="find . -name '*.js'|xargs grep -s "

Notice, that I created two shortcuts, one for php (most common) and one for javascript. For some odd reason, when I tried searching both extensions, it did not work. If anyone knows the reason for this, please leave a comment. After you save your file, source it, like so:

source ~/.bashrc

And now you can use your command, but typing it from anywhere followed by the phrase you want to search for. Finit!

May the force be with you.

Leave a Reply

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