Smart questions
Smart answers
Smart people
INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Member Login




Remember Me
Forgot Password?
Join Us!

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips now!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

Join Tek-Tips
*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Donate Today!

Do you enjoy these
technical forums?
Donate Today! Click Here

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.
Jobs from Indeed

Link To This Forum!

Partner Button
Add Stickiness To Your Site By Linking To This Professionally Managed Technical Forum.
Just copy and paste the
code below into your site.

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

phn737 (TechnicalUser) (OP)
28 May 05 17:25
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.
pcunix (MIS)
28 May 05 17:34
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 http://aplawrence.com

phn737 (TechnicalUser) (OP)
28 May 05 18:22
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.
TrojanWarBlade (Programmer)
28 May 05 18:47
A simple example for you:

CODE

perl -lne '/regex/ and print' file_to_test


Trojan.

KevinADC (TechnicalUser)
28 May 05 19:29
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.
tchatzi (TechnicalUser)
29 May 05 5:29
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 My_word and not my_word it will not match. grep is case sensitive.


``The wise man doesn't give the right answers,
he poses the right questions.''
TIMTOWTDI

pcunix (MIS)
29 May 05 6:22

Quote:

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 http://aplawrence.com

tchatzi (TechnicalUser)
29 May 05 7:21
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

pcunix (MIS)
29 May 05 9:08

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 http://aplawrence.com

tchatzi (TechnicalUser)
29 May 05 9:43

Quote:

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

KevinADC (TechnicalUser)
29 May 05 15:54
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  
pcunix (MIS)
29 May 05 17:33
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 http://aplawrence.com

tchatzi (TechnicalUser)
30 May 05 1:13
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

pcunix (MIS)
30 May 05 5:40
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 http://aplawrence.com

tchatzi (TechnicalUser)
30 May 05 6:20
Exactly!!


``The wise man doesn't give the right answers,
he poses the right questions.''
TIMTOWTDI

KevinADC (TechnicalUser)
30 May 05 13:49

Quote (perluserpengo):


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:

Quote (phn737):


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

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members!

Back To Forum

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close