The Grep Command

The grep command is without a doubt currently my favorite command. Lets say we are writing a large complex application, and we have some method that we don't know who calls it, or some code that is passed in and we have no idea from where or why. We can easily locate our elusive method call with grep -r my_method. The -r option will recursively search the contents of all the files in and below our current directory. We can also call this command as rgrep search_pattern.

~$ grep -r FRAMEWORKS
tasks/release.rb:FRAMEWORKS = %w( activesupport activemodel activerecord actionview actionpack activejob actionmailer actioncable railties )
tasks/release.rb:(FRAMEWORKS + ['rails']).each do |framework|
tasks/release.rb:    (FRAMEWORKS + ['guides']).each do |fw|
tasks/release.rb:    (FRAMEWORKS + ['guides']).each do |fw|
tasks/release.rb:    (FRAMEWORKS + ['guides']).each do |fw|
tasks/release.rb:  task :build           => { |f| "#{f}:build"           } + ['rails:build']
tasks/release.rb:  task :update_versions => { |f| "#{f}:update_versions" } + ['rails:update_versions']
tasks/release.rb:  task :install         => { |f| "#{f}:install"         } + ['rails:install']
tasks/release.rb:  task :push            => { |f| "#{f}:push"            } + ['rails:push']
Rakefile:    FRAMEWORKS.each do |project|
Rakefile:  (FRAMEWORKS - %w(activerecord)).each do |project|

And we have a first hand look at how Rails builds it's framework tasks, if you are in rails's root directory.

If we have no need to traverse multiple files and subfolders, we can specify a specific file by using grep in its most basic form, grep pattern filename.txt we follow the grep command with the pattern to match pattern and then the file to search, filename.txt in this case.

~$ grep require load_paths.rb
require 'bundler'

One of the more useful options is to show the line number of our match. We would accomplish this by adding -n after grep.

~$ grep -n task Rakefile
4:require "tasks/release"
5:require 'railties/lib/rails/api/task'
8:task :build => "all:build"
11:task :prep_release => "all:prep_release"
  ### don't worry, there was a lot more ###

We can call options by specifying either single character -i or writing the full name --ignore-case.

option full name description
`-i` `--ignore-case` ignore case distinctions
`-v` `--invert-match` display everything except our pattern match
`-c` `--count` display only the number of line matches
`-n` `--line-number` prefix line with its line number match

And there are quite a few more options that come with grep, these can be found by using the man grep or grep --help commands.