简体   繁体   中英

cat into perl Regex getting too many matches

Im scraping through a file and trying to find the first occurrence of "silverlight #", where '#' is a version number. Im currently using

cat silver.txt | perl -e 'while ($line = <>) {if ($line =~/Silverlight \d/) { $line =~/(Silverlight \d)/; print "$1\n";}}'

And it works, but since the pattern im looking for is found more than once in the file, I get the following output.

Silverlight 5
Silverlight 5
Silverlight 5
Silverlight 5
Silverlight 5
Silverlight 5
Silverlight 4
Silverlight 4
Silverlight 4
Silverlight 4
Silverlight 3
Silverlight 3
Silverlight 3
Silverlight 3
Silverlight 2
Silverlight 2
Silverlight 2
Silverlight 1

How can i print only the first occurence of the pattern, and not every one in the file?

perl -nE 'say $1 if /(Silverlight \d)/ and not $seen{$1}++;' silver.txt

That says: in an I/O loop over STDIN or the files given as arguments ( -n ), look for the match ( /.../ and $1 ) and print it with a newline ( say implied by -E ) if we haven't already seen ( %seen ) it.

Update

I misread the OP's request for printing the "first occurrence of the pattern" as "the first instance of each distinct match," which is not what he wants. This is what he wants:

perl -nE 'say($1), exit if /(Silverlight \d)/' silver.txt

In this case the parentheses for say are necessary, lest it be understood as say($1, exit) .

If you want to exit after you print one result, why not just exit after you print one result?

cat silver.txt | perl -e 'while ($line = <>) {if ($line =~/Silverlight \d/) { $line =~/(Silverlight \d)/; print "$1\n"; exit }}'

And a simpler version of exactly the same thing:

cat silver.txt | perl -e 'while (<>) {if (/(Silverlight \d)/) { print "$1\n"; exit; }}'

Or:

cat silver.txt | perl -e 'while (<>) { /(Silverlight \d)/ && print "$1\n" && exit; }'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM