user2064000
user2064000

Reputation:

Perl equivalent of grep -Eo

In shell scripting, grep -Eo {regex} {file} returns the matched part of the regex. For example:

$ echo \
'For support, visit <http://www.example1.com/support>
You can also visit <http://www.example2.com/products> for information.'
| grep -Eo 'http://[a-z0-9_.-]+/'

http://www.example1.com/
http://www.example2.com/

How would I do this with Perl?

Upvotes: 0

Views: 469

Answers (2)

Tiago Lopo
Tiago Lopo

Reputation: 7959

To get -o functionality I suggest the following:

echo abcdabcd | perl -lne 'while ($_ =~ s/(bc)//){print $1}'
bc
bc

echo abcdabcd | grep -Eo 'bc'
bc
bc

But for you example I suggest perl -pe 's|(http://[\w-\.]+/).*|$1|g':

echo 'http://www.example1.com/support' | perl -pe 's|(http://[\w-\.]+/).*|$1|g'
http://www.example1.com/

Upvotes: 2

mob
mob

Reputation: 118605

Here are two ways:

  1. In Perl, the special variable $& contains the matched part of the regular expression.

    perl -ne 'print "$&\n" if m#http://[a-z0-9_.-]+/#' < input
    
  2. If your regular expression contains capture groups, the patterns matched by those groups are assigned to the variables $1, $2, ...

    perl -ne 'print "$1\n" if m#(http://[a-z0-9_.-]+/)#' < input
    

Upvotes: 3

Related Questions