Searching a Text File

By Using Grep and Regular Expressions

 

 

Displaying Text

You can put some text in the text file by using your favorable editor. A few words of Jesus are in file askme.txt.

The program cat shows the content of a text file. It works best for short text files. To show what's inside a text file askme.txt, use the cat program, as follows (I'll use the character "_" to denote the end of line in the following examples; it isn't visible in the command line):

>   cat askme.txt_
Ask, and it shall be given you_
Seek, and ye shall find_
Knock, and it shall be opened unto you._
For every one that asketh receiveth_
And he that seeketh findeth_
And to him that knocketh it shall be opened._

    ^

Searching Text

To search a file for lines that have a certain pattern, use the program grep. Finding the pattern find in the text file askme.txt:

>   grep find askme.txt_
Seek, and ye shall find_
And he that seeketh findeth_

To find all occurrences of the pattern knock (including Knock), use the regular expression [Kk]nock:

>   grep [Kk]nock askme.txt_
Knock, and it shall be opened unto you._
And to him that knocketh it shall be opened._

Let's use a regular expression to find lines that contains dots (.):

>   grep \. askme.txt_
Knock, and it shall be opened unto you._
And to him that knocketh it shall be opened._

    ^

Specifying Text Pattern

Regular expression is a text pattern. You can specify a regular expression by using a special kind of language.

Metacharacters are the characters that have special meaning in text patterns. Some metacharacters are:

.     Match any single character except newline
*     Match any number of the characters
\     Turn off the special meaning of the following character
^     Match pattern at the beginning of the line.
$     Match pattern at the end of a line.
[]     Match any one of the enclosed characters

A regular expression find$ describes the pattern find that is at the end of line.

    ^

 

KP.

 

1