linux poison RSS
linux poison Email

How To search for an string in a file using grep

grep searches the input files for lines containing a match to a given pattern list. When it finds a match in a line, it copies the line to standard output (by default), or does whatever other sort of output you have requested with options.

grep can simply be invoked: $ grep 'STRING' filename

This is OK but it does not show the true power of grep. First this only looks at one file. A cool example of using grep with multiple file would be to find all files in a directory that contains the name of a person. This can be easily accomplished using a grep in the following way :

$ grep 'Nikesh J' *

Notice the use of single quotes; This are not essential but in this example it was required since the name contains a space. Double quotes could also have been used in this example.

Grep Regular Expression

grep can search for complicated pattern to find what you need. Here is a list of some of the special characters used to create a regular expression:

`.' The period `.' matches any single character.

`?' The preceding item is optional and will be matched at most once.

`*' The preceding item will be matched zero or more times.

`+' The preceding item will be matched one or more times.    

So an example of a regular expression search would be: $ grep "\<[A-Za-z].*" file

This will search for any word which begins with a letter upper or lower case.

For more details check: $ man grep


1 comments:

Anonymous said...

grep -w is another grep option for exact word matching, one of my favorites. see here for couple of more useful grep examples http://javarevisited.blogspot.com/2011/09/find-hostname-from-ip-address-to.html

Post a Comment

Related Posts with Thumbnails