Question

Have the below perl grep regex and it's working properly.

  my  @cont = grep {/,\s*511747450\s*,\s*CAN2\s*$/} @fileContents;

I want to convert it to unix system grep and I tried the same regex using system command in the below way and it's not working.

  my $cmd="grep ,\s*5117474501\s*,\s*CAN2\s*\$ " . $dirPath . "/" .$fileName;
  my $exitStatus =system($cmd);
Was it helpful?

Solution

\, * and $ are special to the shell. Some more escaping is in order.

use String::ShellQuote qw( shell_quote );

my $pat = ',\\s*5117474501\\s*,\\s*CAN2\\s*$';

my $cmd = shell_quote('grep', '--', $pat, "$dirPath/$fileName");
my $exitStatus = system($cmd);

Or you can simply avoid the shell by using the multi-arg form of system.

my $pat = ',\\s*5117474501\\s*,\\s*CAN2\\s*$';

my @cmd = ('grep', '--', $pat, "$dirPath/$fileName");
my $exitStatus = system({ $cmd[0] } @cmd);

OTHER TIPS

grep doesn't work with \s in bash in some versions.

Try [:space:] instead of \s.

The behaviour of grep varies between different versions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top