What is grep and when/how to use it

Grep is a Unix tool used for searching content within files sitting on the server.

The general syntax of the grep commands is:

  grep [-options] pattern [filename]

You can use fgrep to find all the lines of a file that contain a particular word. For example, to list all the lines of a file named myfile in the current directory that contain the word “dog”, enter at the Unix prompt:

  fgrep dog myfile

This will also return lines where “dog” is embedded in larger words, such as “dogma” or “dogged”. You can use the -w option with the grep command to return only lines where “dog” is included as a separate word:

  grep -w dog myfile

To search for several words separated by spaces, enclose the whole search string in quotes, for example:

  fgrep "dog named Checkers" myfile

The fgrep command is case sensitive; specifying “dog” will not match “Dog” or “DOG”. You can use the -i option with the grep command to match both upper- and lowercase letters:

  grep -i dog myfile

To list the lines of myfile that do not contain “dog”, use the -v option:

  fgrep -v dog myfile

If you want to search for lines that contain any of several different words, you can create a second file (named secondfile in the following example) that contains those words, and then use the -f option:

  fgrep -f secondfile myfile

You can also use wildcards to instruct fgrep to search any files that match a particular pattern. For example, if you wanted to find lines containing “dog” in any of the files in your directory with names beginning with “my”, you could enter:

  fgrep dog my*

This command would search files with names such as myfilemy.hw1, and mystuffin the current directory. Each line returned will be prefaced with the name of the file where the match was found.

By using pipes and/or redirection, you can use the output from any of these commands with other Unix tools, such as moresort, and cut. For example, to print the fifth word of every line of myfile containing “dog”, sort the words alphabetically, and then filter the output through the more command for easy reading, you would enter at the Unix prompt:

  fgrep dog myfile | cut -f5 -d" " | sort | more

If you want to save the output in a file in the current directory named newfile, enter:

  fgrep dog myfile | cut -f5 -d" " | sort > newfile

For more information about grepegrep, and fgrep, enter:

  man grep

more info @indianauniversity

Michael Savin

My name is Michael Savin. I've been contributing to the Internet for over ten years and have been a London based Magento freelancer for the last six.

I build eCommerce websites for varied companies worldwide and enjoy a close relationship with many brands, freelancers and studios. Work aside I enjoy cycling, reading and long walks in sunny days.