The grep Command

team bbl


The grep command is so beloved by Linux users that it has its own t-shirts. The grep command finds files that have specified contents and outputs each line that it finds. The general format for the grep command is:

 grep options pattern files 

where:

  • pattern specifies the text string to search for. pattern can be a literal string, such as abc or xxx. pattern can also be a regular expression, a pattern to be matched, such as any uppercase character or any word that begins with Q. Regular expressions are discussed in Appendix A.

  • files specifies the files to search for the string. files can specify filenames (using wildcards if needed) or a directory.

For example, the following is a simple grep command with its output:

 grep "Mary Poppins" * file1.txt:I like Mary Poppins! file7.txt:Mary Poppins is a great movie. 

The command looks in all the files in the current directory for the string, Mary Poppins. Lines containing the search string display, with the filename prepended. You can use a path (such as /home/janet) instead of *, to specify a directory and all the files in that directory are searched.

The grep command has many options, some of which are shown in Table 7-6.

Table 7-6. Options for the grep Command

Option

What it does

-c

Output the number of lines found, rather than the lines themselves.

-i

Ignore upper- and lowercase when matching.

-l

Output the names of files with matches, rather than the actual lines.

-n

Include the line number of the match: file1.txt:16:Text on line.

-r

Check all subdirectories in the specified directory.

-v

Output all lines that don't match.

-x

Output a line only when the pattern matches the entire line.


    team bbl



    Spring Into Linux
    Spring Into Linux
    ISBN: 0131853546
    EAN: 2147483647
    Year: 2005
    Pages: 362
    Authors: Janet Valade

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net