Unix Commands  «Prev  Next»
Lesson 7 The grep command
Objective Use grep to search text from within a script.

Unix grep Command

The grep command searches a file for a sequence of characters called a regular expression. Regular expressions are search patterns that include a specific set of wildcard characters, also called metacharacters. The following example searches the letter file for the regular expression
^Final exams

$ grep "^Final exams" letter

Final exams are coming up next week.

The caret indicates the regular expression should be located at the beginning of the line.

Patterns stored in variables

Your command can take the regular expression from a variable. You can use this technique inside your shell scripts to allow your user to type in the regular expression interactively. Before we look at a sample script that reads the regular expression from the user, look at the following example below to see how to use a regular expression stored in a variable.

How to use a regular expression stored in a variable.

#!/usr/bin/perl -w
# use strict;

sub test($$)
{
 my $lookfor = shift;
 my $string = shift;
 print "\n$lookfor ";
 if($string =~ m/($lookfor)/)
 {
  print " is in ";
 }
 else
 {
  print " is NOT in ";
 }
 print "$string.";
 if(defined($1))
 {
  print "      <$1>";
 }
 print "\n";
}

test("st.v.", "steve was here");
test("st.v.", "kitchen stove");
test("st.v.", "kitchen store");

The preceding code produces the following output.

[slitt@mydesk slitt]$ ./junk.pl
st.v.  is in steve was here.      <steve>
st.v.  is in kitchen stove.       <stove>
st.v.  is NOT in kitchen store.
[slitt@mydesk slitt]$

Using grep in a shell script

Below is a script that reads a regular expression into a variable and searches the volleylist file for it. The script prompts the user to enter the search information. It reads the input into the info variable. It then uses this variable in the grep command. This script will search the volleylist file for whatever pattern the user enters when the script is run and will print matching lines to the screen. The next lesson shows how to use grep to count the number of lines that contain a regular expression.

#! /bin/sh
echo “Enter information to search for: “
read info
grep “$info” volleylist