Reading a line from a file

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ebmt2006
    New Member
    • Feb 2007
    • 2

    Reading a line from a file

    How do I read a text from a file using perl? What I have is a bunch of text inside a file and I need to read that line I want ONLY.

    What I have reads the whole content inside the file.

    For example:
    I have a file called “file.txt”
    Inside that file
    I have 200 lines of texts
    I want to only to read
    “The script is great good job” and
    “The script is bad try agin”

    And I want to print those two lines
    To a file called “ file.out “

    This is what I have so far and this reads out the whole text and prints the whole 200 lines of text.

    Code:
    #!/usr/bin/perl -w
    #fh2.pl
    
    open FH, 'file.txt' or die "open failed: $!";
    open OUTFH, '> file.out' or die "open failed: $!";
    
    while (<FH>) {
    	print OUTFH "Message: $_";
    }
    close FH;
    close OUTFH;
    Thank you
    Last edited by miller; Mar 16 '07, 10:00 PM. Reason: Code Tag
  • KevinADC
    Recognized Expert Specialist
    • Jan 2007
    • 4092

    #2
    Code:
    #!/usr/bin/perl -w
    #fh2.pl
    
    open FH, 'file.txt' or die "open failed: $!";
    open OUTFH, '> file.out' or die "open failed: $!";
    
    while (<FH>) {
    if (/The script is great good job/ or /The script is bad try again/) {
       print OUTFH "Message: $_";
    }
    close FH;
    close OUTFH;

    Comment

    Working...