grep is one of the most powerful commands in the unix based systems. In this article you can see some basics of it.
Searching a pattern in a single file
You can easily search for exact phrase in a file. For example we will search for the word fail in /var/log/message:
tequila ~ # grep fail /var/log/messages
Jun 17 03:20:59 tequila postfix/smtpd[30186]: _sasl_plugin_load failed on sasl_auxprop_plug_init for plugin: ldapdb
Jun 17 03:26:00 tequila postfix/smtpd[30192]: _sasl_plugin_load failed on sasl_auxprop_plug_init for plugin: ldapdbtequila ~ #
If you get too many lines you can use single quotes to specify more words. For example you can run the same thing like this:
tequila ~ # grep ‘failed on’ /var/log/messages
Jun 17 03:20:59 tequila postfix/smtpd[30186]: _sasl_plugin_load failed on sasl_auxprop_plug_init for plugin: ldapdb
Jun 17 03:26:00 tequila postfix/smtpd[30192]: _sasl_plugin_load failed on sasl_auxprop_plug_init for plugin: ldapdbtequila ~ #
This will print only the lines that contains the words failed on.
Searching a pattern in multiple files
As always you can use *
Most unix commands accept * for all.
For example in order to read all the logs in /var/log and grep some pattern you can use:
tequila ~# grep ‘failed on’ /var/log/*
This will read all the files located in /var/log/ and print you the lines you are looking for. In order see which file contains the word you seek for you can use the option -l.
tequila ~ # grep -l ‘failed on’ /var/log/*
/var/log/messages
tequila ~ #
As you can see this command lists the file that contains the string that you are looking for.
Searching a pattern in multiple files recursively
This is a good one. You can search the whole file system for a specific phrase if you want. In order to do this you need to use the -r option and -l option so it will list you the files that contains this phrase. Also you will need to specify starting location. Here is the example:
tequila ~ # grep -rl ‘failed on’ /*
This will show you how to grep the string failed on recursively for the whole directory tree.
If I have to explain the all the power of grep I can write a book. It’s really good tool. These ware the basics from me.
You can see also: Man Pages | grep in wikipedia | computerhope.com