Wednesday, 14 December 2011

Searching strings with grep command

Let me discuss a situation- I have saved all of my contacts information as separate files and put it in a folder called contacts. I have to find the file which contain the name Mr. John. I get started with opening each files in my text editor and ctr+f to find was too difficult since I have about 300 files to search. But working a little smart I found john in 2 minutes..How ? The grep command .
 Grep is a command-line text-search utility originally written for Unix. The name comes from the ed command g/re/p (global / regular expression / print). The grep command searches the given file for lines containing a match to the given strings or words. grep displays the matching lines by default.
How to use grep command :
1.Searching for a string in a file

                $ grep train vehicles.txt

    the above usage will print all the lines containing the text train from vehicles.txt
2 .Searching in multiple files of same type :

                $ grep train *.txt

    the above command will print all the lines with text 'train' from all the text files in that folder
3. Searching by ignoring case sensitivity (with parameter -i)

                $ grep -i train vehicles.txt

     the above command will search all the 'train' sequences wihtout matching the cases.
4 . Word search

                $ grep -w train vehicles.txt
     Selecting all lines containing train as a word, i.e. surrounded' by white space (speedtrain
     and train  do not not match) may be accomplished with the -w option flag
5. Count lines when words are matched
                $ grep -c 'word' /directory

      grep can count the number of times that the pattern has been matched for each file using -c (count)    option.
6.Search recursively in an entire directory

               $ grep -r 'word' /directory  

   You can search recursively i.e. read all files under each directory for a string .

No comments:

Post a Comment