How to use grep for multiple strings in perl

Posted on 2009-02-16
Last Modified: 2012-06-27
Using perl I need to ssh to a remote host and grep a file for strings.  For example, if I want to search just 'string1'  I would do the line of code below and it works.

$my result = qx{ssh $host grep string1 $log_file};

however I want to search 2 or 3 strings in the file. I tried
$my result = qx{ssh $host grep 'string1\|string2' $log_file};

but that does not work.  
The grep command is right because if execute from the shell prompt I get the lines containing either string1 or string2.
Question by:urivera
    LVL 3

    Assisted Solution

    Try this:

    open(PIPE, "ssh $host grep string1 $log_file |");
    my @output = <PIPE>;

    @output should contain all strings returned by the command
    LVL 3

    Expert Comment

    Oh, in your case command inside 'open' should like as "ssh $host grep 'string1\|string2' $log_file" of course
    LVL 39

    Accepted Solution

    my $result = qx{ssh $host grep -e string1 -e string2 $log_file};
    LVL 84

    Assisted Solution

    qx{ssh $host grep 'string1\\\\\\|string2' $log_file}
    grep /string1|string2/ qx{ssh $host cat $log_file}

    Featured Post

    Highfive + Dolby Voice = No More Audio Complaints!

    Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

    Join & Write a Comment

    I've just discovered very important differences between Windows an Unix formats in Perl,at least 5.xx.. MOST IMPORTANT: Use Unix file format while saving Your script. otherwise it will have ^M s or smth likely weird in the EOL, Then DO NOT use m…
    A year or so back I was asked to have a play with MongoDB; within half an hour I had downloaded (,  installed and started the daemon, and had a console window open. After an hour or two of playing at the command …
    Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
    Here's a very brief overview of the methods PRTG Network Monitor ( offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…

    745 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    16 Experts available now in Live!

    Get 1:1 Help Now