Thursday, August 2, 2007

The 'grep' command

In the last section we talked about the 'find' command which finds files. Now we'll talk about the 'grep' command which finds words in files. Your windows manager may have this incorporated into its find tool but then again, the beauty of Linux is having alternatives.
What does 'grep' mean?

'grep' is a Vulcan word that means "find". Actually it isn't, but it sort of looks like it, doesn't it?

Kirk: "Find the solar system L10J, Mr. Spock."
Spock: "Grepping now, Captain." *

* Star Trek stuff copyright Paramount Pictures

Let's have a little practice session with 'grep'. The best way is learning by doing, so let's do it.
A 'grep' mini-tutorial

With 'pico' or any Linux text editor, create a file called 'mary1.txt'

pico mary1.txt

Then type:

Mary had a little lamb

Press CTRL-X in 'pico' (if you're using that) and it will prompt you to save.

Then create: mary2.txt and enter the text Mary had a little cow.

Save that and create the file: mary3.txt and type: Mary had a little too much to drink. Now we know what Mary was doing when she wasn't watching her lambs! Now save that file.

OK, now we're ready to try out 'grep', so phasers on stun and let's go.

Type the following command:

grep Mary mary*.txt

Let's explain this a little. 'grep' looks for the word "Mary" in any text file that is called "mary(something).txt". You've created three files that start with 'mary', so the asterisk makes sure that 'grep' will look for the word 'Mary' in all three.

You should get this output:

mary1.txt Mary had a little lamb
mary2.txt Mary had a little cow
mary3.txt Mary had a little too much to drink

The word 'Mary' is in all of those files, so you'll get this output.

If you type grep little mary*.txt you'll get the same output because the word "little" is also in each of those files. But if you type the word "cow", you'll get this output:

mary2.txt: Mary had a little cow

because the word "cow" is only in mary2.txt.

Typing grep drink mary*.txt will get us more or less the same, only that mary3.txt will show up instead of mary2.txt.

Well, there's 'grep' in a nutshell. It's been a pleasure 'grepping' with you!

No comments: