Grep is just not for matching lines anymore

Thanks to Owen Kaser, I’ve learned that grep can return just the match, and not the whole line.

These examples say it all:

$ grep Ab phone
505-837-2938 Abby Abbott
212-940-2039 Abel Baker
301-302-3030 Abigail Adams

$ grep –o 'Ab[^ ]*' phone

So, you can get all email addresses in an HTML file using the following syntax (correct me if this is wrong):
grep -o "[a-zA-Z\\.]*@[a-zA-Z\\.]*" somefile

Under Windows, you can use the Win32 port of grep which has this feature. Tim Charron’s port of grep doesn’t have it. Tim Charron’s version is especially convenient since it supports a findutils-like function (grep -S “pattern” *.txt will go in subdirectories) whereas the findutils port to Windows clashes with the Microsoft find command. (Don’t tell me to use cygwin, I already do.)

Grep would be so much more useful however if it supported reluctant quantifiers.

Published by

Daniel Lemire

A computer science professor at the University of Quebec (TELUQ).

One thought on “Grep is just not for matching lines anymore”

Leave a Reply

Your email address will not be published. Required fields are marked *

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    Markdown is turned off in code blocks:
     [This is not a link](

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see