Jump to content

grep (global regular expression print)


rev.dennis
 Share

Recommended Posts

grep is a very powerful tool that you will for sure use often.  You can search through multiple files for specific strings of characters and then view the list of matching files onscreen.


 


To find text strings with grep:



grep djzah db.thezah.com

At the shell prompt, type grep, the text you're trying to locate (in this case djzah), and the file you're searching in (here, db.thezah.com).  grep will return all lines in the file that contain the specified string.



grep -5 djzah db.thezah.com

You can specify that a number of lines (say 5) on either side of the found text string should be displayed.  Sometimes you can't tell what you need to know with just the line that contains your search string, and adding lines around it can help give you a context.  Note: This option isn't available on all versions of grep, but it'll work for most.



grep -c djzah db.thezah.com

By adding the -c flag, you can find out how many times a text string appears in a file



grep -v djzah db.thezah.com

With the -v flag, you can find all of the lines that do not contain the specified string



grep -i djzah db.thezah.com

With the -i flag, you can search without case-sensitivity.  Here any line with djzah or DJzah would be found.


 


TIPS


  • Use the -n flag (for example grep -n djzah db.thezah.com) to print each found line with a  line number.
  • You can use grep with multiple filenames, such as in grep djzah db.*
  • To include spaces you " like grep "Serial Number" db.*

 


To use regular expressions with grep:



grep .jzah db.thezah.com

Type grep followed by the regular expression and the filename.  Here, we've used the regular expression .jzah to find all instances of "jzah" that are preceded by a single character.  NOTE: this usage of a . to match a single character closely resembles the ? wildcard.


You could also use multiple periods for specific numbers of characters.  For example, to find "Dogbert" and "Dilbert" you could use grep D..bert filename


 


 


 


Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • Create New...