Grep

From Psygen Wiki
Revision as of 02:30, 24 December 2016 by Admin (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Usage

grep searches the named file (or files) for the specified string. (You can also use egrep to search inside a file using Regular Expressions )


Case Sensitive

grep bananas filename.txt This searches for the word bananas in the file, filename.txt

Note that the search is case sensitive. It will not find Bananas, or BANANAS.

If you want it to find all of those, use:

grep -i bananas filename.txt


String-Search

grep searches for strings, not words. It will match partial words, whole words, and that string inside a whole block of text.

So, if I'm looking inside a file for the word "the", and I use:

grep the filename.txt

grep will output all of the following:

- the
- themselves
- theory
- another
(etc...)

... wait, we only wanted "the"...

Fortunately, we can tell grep to do that, like so:

grep -w the filename.txt This will tell grep to only match the word "the".


Show Line Numbers

You can make grep show the numbers the match is on:

grep -n candy candylist.txt

This will show the number of the line the match is on, like this:

5: candycanes
18: cotton candy is yummy, too
42: Candy bars:

This is very convenient when you're greping for something, and want to edit that line in the file in vim

egrep

If you have a complex search term, you can use Regular Expressions with egrep.

Usage:

egrep 'Regular Expression here' filename.txt

Like this:

egrep '[aeiou]{3,}' filename.txt

This will find any three vowels that are right next to each other in filename.txt You can put any Regular Expressions inside the single quotes.

References

  1. grep man page
  2. Geek Stuff grep Examples