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.

Note
I'll use the character ">" to denote the prompt of the command interpreter and the character ";" for the end of line in following examples (second character isn't visible in the command line).

Well, use cat to see what's inside the text file askme.txt:

>   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

For example, a regular expression find$ describes the pattern find that is at the end of line.

    ^

 

KP.