Grep Command Tutorial For Unix
grep Basics
There are two ways to employ grep. The first examines files as follows:
grep regexp filename
grep searches for the designated regexp in the given file (filename). The second method of employing grep is when it examines “standard input.” For example:
cat filename | grep regexp
In this case, the cat command will display the contents of a file. The output of this command is “piped” into the grep com- mand, which will then display only those lines that contain the given regexp. The two commands just shown have identical results because the cat command simply passes the file un- changed, but the second form is valuable for “grepping” other commands that alter their input.
When grep is called without a filename argument and without being passed any input, it will let you type in text and will re- peat it once it gets a line that contains the regexp. To exit, press Ctrl-D.
At times, the output is remarkably large and hard to scroll through in a terminal. This is usually the case with large files that tend to have repetitious phrases, such as an error log. In these cases, piping the output to the more or less commands will “paginate” it so that only one screen of text is shown at a time:
grep regexp filename | more
Another option to make the output easier to look at is to redi- rect the results into a new file and then open the output file in a text editor at a later time:
grep regexp filename > newfilename
Also, it may be advantageous to look for lines that contain sev- eral patterns instead of just one. In the following example, the text file editinginfo contains a date, a username, and the file that was edited by that user on the given date. If an adminis- trator was interested in just the files edited by “Smith”, he would type the following:
cat editinginfo | grep Smith
The output would look like:
May 20, 2008 | Smith | hi.txt |
June 21, 2008 | Smith | world.txt |
An administrator may wish to match multiple patterns, which can be accomplished by “chaining” grep commands together. We are now familiar with the cat filename | grep regexp com- mand and what it does. By piping the second grep, along with any number of piped grep commands, you create a very refined search:
cat filename | grep regexp | grep regexp2
In case of any ©Copyright or missing credits issue please check CopyRights page for faster resolutions.