Useful bash command for ruby programming (find a string within a file including sub directory files)

Here’s a useful bash command, great for finding the source of any ruby “unintialized constant” errors.


steve@Steve-Root-MBP$grep -r 'Spree::Admin::Application' .

Returns the file name and the line with the matching string, like:

./app/controllers/spree/admin/satisfies_controller.rb: class Spree::Admin::SatisfiesController < Spree::Admin::ApplicationController

So, my constant that caused the error is located in app/controllers/spree/admin/satisfies_controller.rb

The command is made up like this:
grep = grep is a command-line utility for searching plain-text data sets for lines matching a regular expression
-r = recursively search all the sub directories
'Spree::Admin::Application' = The Needle = the string you want to search for, I enclose in apostrophes, I think you can use speech marks etc. You can also use a regular expression to match things
. = The Haystack = Where you want to search, using just a dot means search every every file.

grep can do much more, read the man file (grep man) or google for more ideas. The other cool thing I do all the time is use grep to extract data from a log file and output it to another file. For example;

grep '111.222.333.444' apache.log > analyse.txt

Here, any log line that has '111.222.333.444' will be copied into the file analyse.txt. This is an IP address, but it could just as easily match dates, pages, referrer strings and so on.

Leave a Reply

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