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'dHow do I do this (with grep or another Unix/Windows command-line tool)?
12 Answers
Use the -o option:
grep -E -i -o "we'[a-z]+" file.txtNote that this is not universally portable to all grep implementations, though.
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