Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

how to seach for a specific string in a file; using grep in perl

Status
Not open for further replies.

phn737

Technical User
Nov 4, 2002
31
US
hello,
i would like to search a file to see if a specific string exist and return true or false. not sure how to use grep within perl, is this possible? please help.
thanks.
 
Depends on what you mean. There's a "grep" within Perl, and of course there is the command line grep.

Within Perl, grep searches a list and returns another list:

open(F,"yourfile");
@list=<F>;close F;
$this="String I want";
@f=grep /$this/,@list;

The @f has the matching lines:

If you want to use the command line Perl, call it with backticks or system:

@f=`grep stuff yourfile`;

Does that help?

Tony Lawrence
Linux/Unix/Mac OS X Resources
 
Thank you for your reply.
Yes, this helped. I was thinking of use perl's grep function (from a win32 environment...).

But i am not there yet, your code will put the entire line containing the matched string in the array @f. Is there a way to get just the matching string (which is a single word only not entire line)? I tried grep -w but it's no good. And how do I check if @f contains the string to return true/false?

what about other alternative without using perl's grep; i was doing some reading and a few commented that grep might slow down the task as it has to read entire file.

I would like to check if a specific string exist in a file and return true or false.
 
A simple example for you:

Code:
perl -lne '/regex/ and print' file_to_test


Trojan.

 
one possibility:

Code:
#!perl  
use strict;  
use warnings;

my $word = 'cat';
my $string = findit();

if ($string) {
   print 'true';
}
else {
   print 'false';
}	

sub findit {
   while (<DATA>) {
     print "$_";
     return(1) if index($_,$word) > -1;
   }
}

__DATA__
here is a dog
here is a pig
a horse is here
a cat is here
a cow is here
here is a horse

prints:

Code:
here is a dog
here is a pig
a horse is here
a cat is here
true

which shows it breaks out of the loop as soon as it finds a true match. using index will also be a bit faster than using a regexp unless you need some wild card matching (ie: cats, catch, cattle, etc etc etc) then you have to use a regexp.
 
is that easy
Code:
#!/usr/bin/perl -w
open(FILE,"my_foo");
if (grep{/my_word/} <FILE>){
   print "word found\n";
}else{
   print "word not found\n";
}
close FILE;
remember, if your word in the file is [red]My_word[/red] and not [red]my_word[/red] it will not match. grep is case sensitive.


``The wise man doesn't give the right answers,
he poses the right questions.''
TIMTOWTDI
 
if your word in the file is My_word and not my_word it will not match. grep is case sensitive.

Code:
@stuff=qw(one two three four);
print "@stuff";
@f=grep /Three/i,@stuff;
print "\n",@f;

Tony Lawrence
Linux/Unix/Mac OS X Resources
 
pcunix I didn't want to give him too much info for a start.

It's easier to take one step at a time.

But if you want to make your post look complete, give a link to -> perlre


``The wise man doesn't give the right answers,
he poses the right questions.''
TIMTOWTDI
 
I certainly understand and agree with the sentiment that you don't want to give too much information at once. However, saying that grep is case insensitive is wrong information, so that needed correction.

There are other things in this thread that could use expansion: for example, the idea of reading the file line by line only makes sense if the file is large enough that the whole thing hasn't been read into cache already. But that's the kind of thing that probably doesn't need to be pointed out : it's an efficiency issue that could lead down all sorts of twisty passages - not worth getting into here.



Tony Lawrence
Linux/Unix/Mac OS X Resources
 
However, saying that grep is case insensitive is wrong information, so that needed correction.
I said sensitive not insensitive, but what i wanted to say was 'grep and the regex this way is case sensitive'.
If he doesn't know how to use regex, he would think it doesn't work, in case of copy and paste to his own code.
Don't take it personal though, my post did need a corection, by adding "and the regex this way".


``The wise man doesn't give the right answers,
he poses the right questions.''
TIMTOWTDI
 
if I may, without sounding too anal retentive, grep is neither case sensitive nor insensitive. grep is just a way to do a loop through an array or file or list of some sort. You have to provide grep with arguments to return results, which could be practically anything.

@big_numbers = grep { $_ > 100000000 } @numbers;

I'll go back to my room now [peace]
 
Absolutely correct. And it's even worse than that:

Code:
#!/usr/bin/perl
@num=qw(axc ace def cab ghi);
@f=grep {$_="x $_" if /ab/} @num;
print @f;

is a bit unexpected if you don't realize that grep is an iterative operator.

Tony Lawrence
Linux/Unix/Mac OS X Resources
 
Yes we all know that the regex i wrote is case sensitive and not grep itself. grep has nothing to do with case sesitivity.
And i appologise from all about my typo mistake.
I was a little upset, because the man asked how can he use grep to find a word in a file and everybody told him how to do it except of an understandable way of using grep.
You all can understand that the man does not have much knowledge of perl, so there is no need to give him a hard time.
So i forgot to write that using the regex this way will match exactly the word -> is case sensitive the way i wrote it.
That was what i wanted to write. I appologise for the inconvenience.
And i appologise for driving this post to the wrong direction.


``The wise man doesn't give the right answers,
he poses the right questions.''
TIMTOWTDI
 
I don't know why you are apologising.

Personally, I think it's interesting when a post goes off into the more esoteric details. As you note, that may be too much for the original poster (though who knows?) but other people read threads and may pick up things from the nit-picking.

As to your "mistake", big deal. We all phrase things wrong now and then, so what? I'm quite sure that everyone who read this understood what you meant if they already knew how grep works and the ones who didn't got to learn something.



Tony Lawrence
Linux/Unix/Mac OS X Resources
 
Exactly!!


``The wise man doesn't give the right answers,
he poses the right questions.''
TIMTOWTDI
 
perluserpengo said:
I was a little upset, because the man asked how can he use grep to find a word in a file and everybody told him how to do it except of an understandable way of using grep.

Not true perluserpengo, see quote below:

phn737 said:
what about other alternative without using perl's grep; i was doing some reading and a few commented that grep might slow down the task as it has to read entire file.

but certainly no big (or even small) deal.

I have nothing but respect for the many great answers you post on this forum perluserpengo and would never want to upset you, even if for a moment. I know I appreciate corrections/amplifications to any posts I make, especially from the many knowledgable regulars on this great forum, one of which is yourself. I consider it more like team work and maybe some friendly rivalry, in which everyone benefits, most of all the less experienced people that read this forum or asks questions.

Respectfully,
Kevin
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top