Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Returning line numbers of a string

by pts491 (Initiate)
on Aug 12, 2012 at 22:32 UTC ( #986986=perlquestion: print w/ replies, xml ) Need Help??
pts491 has asked for the wisdom of the Perl Monks concerning the following question:

I am looking to write a script that will search a file for a specific string and then return the line number that contains that string. Any help would be much appreciated!

Comment on Returning line numbers of a string
Re: Returning line numbers of a string
by Marshall (Prior) on Aug 12, 2012 at 22:43 UTC
    Adjust as you will:
    #!/usr/bin/perl -w use strict; while (<DATA>) { print "$. $_"; # $. is current line number } =prints 1 some line 1 2 some line 2 3 some line 3 =cut __DATA__ some line 1 some line 2 some line 3
Re: Returning line numbers of a string
by Old_Gray_Bear (Bishop) on Aug 12, 2012 at 22:47 UTC
    In pseudo-code:
    open log-file set line-counter to 0 read the log-file a line at a time add one to the line-counter if the pattern is found, then then print "I found pattern at ", line-counter once the file is completely read, close log-file print "We Are Done!!" exit
    Let us know when you get stuck implementing this in Perl.

    ----
    I Go Back to Sleep, Now.

    OGB

Re: Returning line numbers of a string
by Anonymous Monk on Aug 12, 2012 at 22:54 UTC
    It is called "grep."
Re: Returning line numbers of a string
by BrowserUk (Pope) on Aug 12, 2012 at 23:26 UTC
    perl -nle"/thesearchstring/ && print $." theFile

    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.

    The start of some sanity?

Re: Returning line numbers of a string
by pvaldes (Chaplain) on Aug 13, 2012 at 17:28 UTC

    oups... duplicated message, sorry.

    to be reaped
Re: Returning line numbers of a string
by pvaldes (Chaplain) on Aug 13, 2012 at 17:31 UTC
    open my $file, '<', "myfilename"; while (<$file>){ next unless /mystring/; print "string found at line $."; } close $file;

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://986986]
Approved by Old_Gray_Bear
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (7)
As of 2014-12-21 14:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (106 votes), past polls