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

2 Answers

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

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

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy