Find the answer to your Linux question:
Results 1 to 5 of 5
Do we have any thing in place of bash's gerp in perl. I want to search a "string" in a file and then want to print whole line in of ...
  1. #1
    Linux Newbie
    Join Date
    Jan 2008
    Posts
    114

    can I find a "string" in a file and print the matching string's line using Perl

    Do we have any thing in place of bash's gerp in perl.

    I want to search a "string" in a file and then want to print whole line in of that matching "string".

  2. #2
    Linux Engineer Javasnob's Avatar
    Join Date
    Jul 2005
    Location
    Wisconsin
    Posts
    942
    You could do this:

    Code:
    my $pat = qr/\Q$string\E/;
    my $fh;
    open $fh, $pathToFile or die "Unable to open $pathToFile: $!\n";
    
    while(<$fh>) {
        chomp;
         print "$_\n" if(/$pat/);
    }
    close $fh;
    That code will search for a string as-is. Let me know if you have any questions; most of them can probably answered by perlre - perldoc.perl.org.
    Flies of a particular kind, i.e. time-flies, are fond of an arrow.

    Registered Linux User #408794

  3. #3
    Linux Newbie
    Join Date
    Jan 2008
    Posts
    114
    Thanks for helping again,

    I have used grep and its working fine.

    while (<*.txt>){
    $test = `grep -ir "provide" $_`;
    }

    Do you think it may give problem later in future???

  4. #4
    Linux Engineer Javasnob's Avatar
    Join Date
    Jul 2005
    Location
    Wisconsin
    Posts
    942
    That shouldn't be a problem, but just a point of style: You shouldn't use the diamond glob operator; it's much better/clearer to use glob().
    Flies of a particular kind, i.e. time-flies, are fond of an arrow.

    Registered Linux User #408794

  5. #5
    Linux Newbie
    Join Date
    Jan 2008
    Posts
    114
    If line is following
    #decided: Answer Yes
    or
    provision: ST_SYS

    then from first line I want only: "Answer Yes"
    and from second line: "ST_SYS"

    I used following trick to get that

    $desc =~ s/^#decided:\s+//i;
    $test =~ s/^provision\s+//i;

    but in below case its failing, its giving me below item instead of blank lines
    #decided:
    provision:

    Please suggest

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...