Basics of Using Grep

Grep is a command line utility that was originally written for use with the Unix operating system. Given a list of files or standard input to read, grep searches for lines of text that match one or many regular expressions, and outputs only the matching lines.

Grep allows you to search files for symbols or strings (groups of characters like words) and will return the files that the search sting is found in. For example you want to search a website’s access log file for a recent traffic that came from a search engine. Most search engine referral urls have a question mark in them. The Grep command would look something like this:

grep [search string] [file name]

For instance, if we had a file.txt and that had 3 lines within it as follows:

who needs windows
in a world without doors?
-signed unknown

and we typed grep “unknown” file.txt, the standard output should print the line “-signed unknow” to the screen.   As a general practice I tend to put the search string within double quotes in case I enter a symbol that may throw grep off, or if i’m looking for multiple words with spaces within.

grep can also parse standard output piped from other commands as well.  For instance,

if  we change to the /etc/ directory:

cd /etc/

and we want to know if the fstab file resides in this directory, we can do an ls -al and pipe that to grep searching for the file name we’re after like so:

etc$> ls -al | grep fstab

The standard output should show that the fstab file exists in that directory listing.

Related Posts

Tags:

Leave a Reply