Using Grep

Global Regular Expression Print is the rather un-catchy full name of grep, the staple of any Linux users toolkit. It is a search tool run from the command line that is evolved directly from Unix, and is so useful it deserved a post of its own.
Grep doesn’t search characters, it searches patterns. This means it is a very powerful and configurable tool. You can search specifics, duplicates and use wildcards. The format is
grep [option] pattern [file]

Or more understandably
grep [what to search for] [in these files]
Here is a very basic outline of how to use grep.
Create a file called ‘Ferrari1.txt’ then type ‘Ferrari F430. Sweet wheels’.
Save the file and create another called ‘Ferrari2.txt’ and enter the text ‘Ferrari 360 Maranello. Nice’.
Save that and create another file called ‘Ferrari3.txt’ and type ‘Ferrari F50 Close but no cigar’ and save the file. Obviously I’m just messing around here, you can put whatever you want in the files, but the scheme needs to be the same.

To try grep we need to type the following command:
grep Ferrari ferrari*.txt
grep looks for the word “Ferrari” in any text file that is called “ferrari(something).txt”. You’ve created three files that start with Ferrari, so the asterisk makes sure that grep will look for the word ‘Ferrari’ in all three.

You should see something like this:
Ferrari1.txt Ferrari F430. sweet wheels
Ferrari 2.txt Ferrari 360 Maranello. Nice and sweet
Ferrari3.txt Ferrari F50 sweet but no cigar
The word ‘Ferrari’ is in all of those files, so you will see this output.
If you type ‘grep sweet Ferrari*.txt’ you would get the same output because the word “sweet” is also in each of those files. But if you type the word ‘cigar’,
you would see this output:
Ferrari3.txt Ferrari F50 sweet but no cigar
because the word “cigar” is only in Ferrari3.txt.
Typing ‘grep wheels Ferrari*.txt’ will get us the same kind of result, only that Ferrari1.txt will show up instead of Ferrari3.txt.
To move a step along a bit you can add ‘–i’ to your command to ignore case sensitivity in the search.
Grep –i wheels Ferrari*.txt
This would display anything with either wheels, or Wheels in the text.
How about a recursive search? Say you wanted to find every instance of the word ‘button’ in your /etc directory.
grep –ri ‘button’ /etc
This command would the display every instance of the word button in your /etc directory. You may have noticed the quotes around button. This tells grep that button is part of the query and not the search destination.
More wildly, what about if you wanted to search for a filename that had a number, but didn’t know what the number was? For example a version number of a particular file you needed.
ls ¦ grep ‘[[:digit:]]’
This uses something called a regular expression which will search for any filename that contains a number, wherever it may be.
That is a very basic illustration of grep. A very powerful and time saving tool that you should come to love the longer you spend with it.