3

Usually, grep searches for all lines containing a match for the pattern/parameter I specify.

I would like to match just the pattern (i.e. not the whole line).

So, if a file contains the lines:

We said that we'll come.
Unfortunately, we were delayed.
Now, we're on our way.
Didn't I say we'd come?

I want to find all contractions starting with "we" (regex pattern: we\'[a-z]+/i); I'm looking for the output:

we'll
we're
we'd

How do I do this (with grep or another Unix/Windows command-line tool)?

1
  • I took a look at the 'grep' man page: linux.die.net/man/1/grep and nothing suggested what you want is possible. You might want to try using 'sed' or 'awk'. If really feeling adventurous, even write a 2-5 line script in PERL.
    – Rolnik
    Jan 3, 2011 at 20:41

2 Answers 2

3

Use the -o option:

grep -E -i -o "we'[a-z]+" file.txt

Note that this is not universally portable to all grep implementations, though.

1
  • My grep has it, so that works for me!
    – palswim
    Jan 5, 2011 at 0:38
0

I'd prefer Perl for something like this:

#!/usr/bin/perl

use strict;
use warnings;

open FH, "< parse.txt" or die $!;

while(<FH>)
{
    while($_ =~ /\b(we\'\w+)\b/g)
    {
        print $1."\n";
    }
}

close FH;

Input text:

Some text we're test we'll why we're.
More text we'll we're.
Test.

Output:

we're
we'll
we're
we'll
we're
2
  • Instead of hardcoding the filename, you should make it accept a filename as an argument and work as a filter. Also, I believe the OP wanted case-insensitive. Jan 3, 2011 at 21:35
  • @Dennis it was an example...
    – user1931
    Jan 3, 2011 at 23:10

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .