Wednesday, March 20, 2013

How to Use Grep Command

Description
The grep command searches an input for the regular expression (pattern of characters) that you specify and displays every line that contains the pattern. Your input can be one or more files or an output of a command using pipes.

Command Syntax
grep [options] PATTERN [file(s)]

OPTIONS
-n display line number of match
-i case-insensitive 
-l list only filenames that contain a match, once each
-w expression is search for as a word

Note: If your regular expression contains a special character, you must enclose it with single quotation marks because these special characters may have a special meaning to your shell. The single quotes prevents the shell from interpreting them. If you are searching against multiple files that contains the regular expression, the name of the file will be displayed in the output.

Usage
The file content given below is used to demonstrate the usage of grep.
#testFile.txt
Color        Phone        Date
red        1-800-123-1234    
orange        1-234-567-8900    March 20, 2013
yellow        1-323-654-8343
green        1-354-675-4323
blue        1-321-645-1423    Feb 1, 2010
indigo        1-800-353-1325
violet
ReD

Regular characters
#Search lines containing red
grep red testFile.txt
#Results
red        1-800-123-1234

#Ignore case with line numbers displayed
grep -in red testFile.txt
#Results 
3:red        1-800-123-1234    
10:ReD

With Regular Expressions
#Search lines that contain a date
grep '[A-Z][a-z]* [0-9]\{1,2\}, [0-9]\{4\}' testFile.txt
#Results
orange        1-234-567-8900    March 20, 2013
blue        1-321-645-1423    Feb 1, 2010

#Search lines that has a 1-800 phone number
grep -n '1-800-[0-9]\{3\}-[0-9]\{4\}' testFile.txt
#Results
3:red        1-800-123-1234    
8:indigo        1-800-353-1325

With Pipes
#Check if a specific port is in use
netstat -anp | grep ":3306"

#Display cpu Model
cat /proc/cpuinfo | grep -i 'Model'

#Check if mysql process is running
ps -ef | grep mysql

Recursive Search
#Display files names that contain "blue"
grep -lr blue *

No comments:

Post a Comment