Link to home
Start Free TrialLog in
Avatar of Nusrat Nuriyev
Nusrat NuriyevFlag for Azerbaijan

asked on

find matching pattern in perl using command line and output matching itself (if found).

How to find match in perl using command line?
Okay, I can even substitute using

perl -i.bak -pe 's/pattern1/pattern2/g' inputFile

How to just find match and output catches?
perl -pe 'if ($_ =~ m/$.+?src(.+?)^/) {print "$1\n"}' inputFile
Avatar of ozo
ozo
Flag of United States of America image

perl -pe 'print if /pattern1/' inputFile
perl -lpe 'print $1 if /src(.+?)/' inputFile
Avatar of Nusrat Nuriyev

ASKER

perl -pe 'print if /pattern1/' inputFile

It outputs all lines no matter what pattern is given.
perl -lpe 'print $1 if /src(.+?)/' inputFile


also outputs all and  whole lines , no matter of pattern

Generally
perl -pe '' inputFile
outputs all content of file is
Is that expected behavior?
As I understand if no code, then it just iterates but should not output.

the behaviour of -p:

while (<>) {
   ... # your script
} continue {
   print or die "-p destination: $!\n";
}
ASKER CERTIFIED SOLUTION
Avatar of ozo
ozo
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Notice the use of the empty file input operator, which will read all of the files given on the command line a line at a time. Each line of the input files will be put, in turn, into $_ so that you can process it. As a example, try:

  $ perl -n -e 'print "$. - $_"' file

This gets converted to:

  LINE:
    while (<>) {
      print "$. - $_"
    }

This code prints each line of the file together with the current line number.

The -p option makes that even easier. This option always prints the contents of $_ each time around the loop. It creates code like this:

  LINE:
    while (<>) {
      # your code goes here
    } continue {
      print or die "-p destination: $!\n";
    }