saumitra121 has asked for the wisdom of the Perl Monks concerning the following question:

I have a file which have data like
this is some data this is other data this is new data
Now I want to check(using a regex) whether a pattern exist in file or not. If yes then print the matched text and exit. In case the pattern occurs more than once, then the one liner should break after first match.

Lets for example say that I want to check for pattern "data" in my file. I am using following one liner.

perl -ne'/(data)/ && print $1' file.txt
The problem with this is that it is NOT exiting after first match and prints matched content thrice.

How can I modify this so that execution will stop after first match?

Please note that instead of "data" i can provide any regex. Also I can't use a script. This has to be a command line one liner in perl(no awk or grep). File size can be as big as 2 GB.

Replies are listed 'Best First'.
Re: Break one liner command line script after first match
by McA (Priest) on Oct 30, 2013 at 12:03 UTC

    Hi

    why not just exiting after printing the matched line?

    UPDATE: perl -ne'/(data)/ && print($1) && exit' file.txt

    McA

      Or die!

      perl -ne'/(data)/ && die $1' file.txt
Re: Break one liner command line script after first match
by 2teez (Vicar) on Oct 30, 2013 at 12:51 UTC

    How can I modify this so that execution will stop after first match
    You can do: perl -ne'/(data)/ && print $1 and last' file.txt

    If you tell me, I'll forget.
    If you show me, I'll remember.
    if you involve me, I'll understand.
    --- Author unknown to me

      Hi,

      as you showed it with your solution: Be aware of the subtle difference between:

      perl -ne'/(data)/ && print $1 and last' file.txt perl -ne'/(data)/ && print $1 && last' file.txt

      That may bite someone (by the way: I was bitten ;-) )

      McA

        Hi,
        Be aware of the subtle difference between:

        perl -ne'/(data)/ && print $1 and last' file.txt perl -ne'/(data)/ && print $1 && last' file.txt
        Of course, I saw the subtle difference, and how you used
        .. print ($1) ...

        the parentheses which is effectively the same thing if "and" is used instead of "&&"
        check this:

        Using
        perl -MO=Deparse -ne'/(data)/ && print $1 && last' file.txt
        you gets:
        LINE: while (defined($_ = <ARGV>)) { print $1 && last if /(data)/; }
        but using
        perl -MO=Deparse -ne'/(data)/ && print ($1) && last' file.txt
        gives:
        LINE: while (defined($_ = <ARGV>)) { last if /(data)/ and print $1; }
        Which is same as this:
        perl -MO=Deparse -ne'/(data)/ && print $1 and last' file.txt
        LINE: while (defined($_ = <ARGV>)) { last if /(data)/ and print $1; }

        If you tell me, I'll forget.
        If you show me, I'll remember.
        if you involve me, I'll understand.
        --- Author unknown to me