Operating System - HP-UX
1752777 Members
6430 Online
108789 Solutions
New Discussion юеВ

Multiple word 'grep' in perl

 
SOLVED
Go to solution
Umesh_1
Occasional Contributor

Multiple word 'grep' in perl

How to know whether the multiple word grep is success or failure.
Simple
4 REPLIES 4
Robin Wakefield
Honored Contributor

Re: Multiple word 'grep' in perl

Hi,

If I run the following perl script:

#!/opt/perl5/bin/perl

@words=qw(mary had a little lamb);
@matches=grep /(m|b)/, @words;
$match=grep /(m|b)/, @words;
print "$match,@matches\n";

I get the following result:

2,mary lamb

Is this what you are after?

Rgds, Robin
Umesh_1
Occasional Contributor

Re: Multiple word 'grep' in perl

Hi Robin,

Thanks for your reply, the question I have is how to grep for a multiple word string in a file and know its result.

Sorry, may be the question that I asked is too abstract. I will put it a little better this time.

There is a file by name aaa which contain name, both first name and second name. In perl we can use the command
-----------------------------
system("grep /'$name/' aaa");
-----------------------------
where $name is a variabe having name of a person such as "Anil Bhat" and aaa is the filename.
To know the result we can see the $? variable. But this is returning 256 every time.

Thanks and regards,
Umesh
Simple
Rodney Hills
Honored Contributor
Solution

Re: Multiple word 'grep' in perl

How come you have /'$name/'?

Did you instead want back-slashes-- \'$name\' to protect the single quote?

The slashes are being passed as part of the string to grep, just use '$name'. Since you started you literal string with double quote, the single quotes do not need any special "escapes".

-- Rod H
There be dragons...
Robin Wakefield
Honored Contributor

Re: Multiple word 'grep' in perl

Hi,

I created a script containing:

#!/usr/bin/perl

$file="/tmp/grep.in";
$name="robin wakefield";
system ("grep '$name' $file");
print $?,"\n";

When "robin wakefield" is found, $?=0
When it isn't found $?=256

I think you should remove the / characters.

Rgds, robin.