Finding patterns in files using your buddy grep

Use grep <pattern> <filename> [<filename>]. The grep command displays lines in the files matching <pattern> as well as the name of the file from which the matching lines come from. The command grep has many useful command line options. Please see its man page for more information. Here we will show some examples of a typical usage of grep.

The option -n makes grep display the line number in front of the line that contains the given pattern. For example:

[alice@onyx examples]$ ls
chap01  chap02  chap03  chap04  chap05  chap06  chap07  extras  file-io  
graphics  Makefile  README.md  UML

[alice@onyx chap06]$ grep JButton TimerDemoPanel.java 
import javax.swing.JButton;
        private JButton startButton;
        private JButton stopButton;
                startButton = new JButton("Start");
                stopButton = new JButton("Stop");
                        JButton clicked = (JButton) e.getSource();

[alice@onyx chap06]$ grep -n JButton TimerDemoPanel.java 
6:import javax.swing.JButton;
31:     private JButton startButton;
32:     private JButton stopButton;
78:             startButton = new JButton("Start");
82:             stopButton = new JButton("Stop");
98:                     JButton clicked = (JButton) e.getSource();
[alice@onyx chap06]$

The option -v inverts the search by finding lines that do not match the pattern.

The option -i asks grep to ignore case in the search string.

A very powerful option is the recursive search option, -r, that will makegrep search recursively in a directory or directories. For example, the following command searches for all files with the string “Crow” in them.

[alice@onyx examples]: grep -r "Crow" C-examples/
C-examples/plugins/plugin1.c:/* Author: Dan Crow
C-examples/plugins/plugin2.c:/* Author: Dan Crow
C-examples/plugins/runplug.c:/* Author: Dan Crow (modified by Amit Jain)
[alice@onyx examples]:

Programmers often use this option to quickly search for a declaration of a variable or class in a large project consisting of hundreds or thousands of files in many directories and subdirectories. This is often called “grepping” the source! See the following for an example.

[alice@onyx examples]$ ls
chap01  chap02  chap03  chap04  chap05  chap06  chap07  extras  file-io  
graphics  Makefile  README.md  UML

[alice@onyx examples]$ grep -r JTabbedPane *
chap06/LayoutDemo.java:  import javax.swing.JTabbedPane;
chap06/LayoutDemo.java:         JTabbedPane tp = new JTabbedPane();
[alice@onyx examples]$

Note that the asterisk (*) matches all directories in the examples folder. We could also have used: grep -r JTabbedPane . (using dot for the current directory)