1

My question is simple as my title says "What is perl's equivalent one liner of grep -o?". That is print the matched regex only instead of whole line?

perl -pe some_option?? 'm/regex/' file
user15964
  • 2,507
  • 2
  • 31
  • 57
  • See also: [grep -P no longer works how can I rewrite my searches](http://stackoverflow.com/questions/16658333/grep-p-no-longer-works-how-can-i-rewrite-my-searches/16658690). (Not a Perl-specific question, but the top answer answers this question.) – ikegami Apr 01 '17 at 17:11

3 Answers3

3

If you want to do the minimal amount of work, change

grep -o -P 'PATTERN' file

to

perl -nle'print $& if m{PATTERN}' file

So from

grep -o -P '(?<=foo)bar(?=baz)' file

you get:

perl -nle'print $& if m{(?<=foo)bar(?=baz)}' file

However, it can be simpler to use a capture.

perl -nle'print $1 if /foo(bar)baz/' file
ikegami
  • 367,544
  • 15
  • 269
  • 518
0

You could just change the code:

perl -ne 'if(/(regex)/) {print "$1\n"}' file
sdocio
  • 132
  • 1
  • 4
0
perl -nE 'say $& while /regex/g' file
Borodin
  • 126,100
  • 9
  • 70
  • 144