krishna reddy
krishna reddy

Reputation: 53

How to grep square brackets in perl

I am trying to grep [0](including square brackets) in a file using perl, I tried following code

my @output = `grep \"\[0\]\" log `;

But instead of returning [0], it is giving output where it matches 0

Upvotes: 4

Views: 531

Answers (1)

Dave Cross
Dave Cross

Reputation: 69224

Your problem is that you need to escape the [ and ] twice, as [ ... ] has a special meaning in regexes (it defines a character class).

#!/usr/bin/perl

use strict;
use warnings;

my @output = `grep "\\[0\\]" log `;

print for @output;

But you really don't need to use the external grep command. Perl is great at text processing.

#!/usr/bin/perl

use strict;
use warnings;

while (<>) {
  print if /\[0\]/;
}

My solution reads from any file whose name is given as an argument to the program (or from STDIN).

Upvotes: 3

Related Questions