Grep in Perl - Searching through multiple files


 
Thread Tools Search this Thread
Top Forums UNIX for Dummies Questions & Answers Grep in Perl - Searching through multiple files
# 1  
Old 04-21-2012
Grep in Perl - Searching through multiple files

I'm attempting to use grep in Perl with very little success.

What I would like to do in Perl is get the output of the following grep code:
Code:
grep -l 'pattern' *

This gives me a list of all the files in a directory that contain the pattern that was searched.

My attempts to do this in Perl have failed so far:

Code:
	my $dir = "/cygdrive/c/TEMP; 
	opendir (my $dh, $dir) or die "Can't open $dir: $!";
		my @allFiles = grep { -f "$dir/$_" } readdir($dh);
	closedir $dh;
	
	my @legFiles = grep {/pattern/} @allFiles;
	foreach (@legFiles) {print "$_\n"};

The above code is looking at the file names and not the contents of the files.

So my question is, how to can I use grep in perl to give me a list of the files that contain a certain pattern?

Thanks in advance.
# 2  
Old 04-21-2012
Hi.

The grep operator/function in perl looks at lists, not files:
Code:
       grep BLOCK LIST
       grep EXPR,LIST
               This is similar in spirit to, but not the same as, grep(1) and
               its relatives.  In particular, it is not limited to using
               regular expressions.

               Evaluates the BLOCK or EXPR for each element of LIST (locally
               setting $_ to each element) and returns the list value
               consisting of those elements for which the expression evaluated
               to true.  In scalar context, returns the number of times the
               expression was true.
-- excerpt from perldoc -f grep, q.v.

If I were doing this and it needed to be in perl, I would probably use system or qx to run the OS command grep with appropriate options. See perldoc -f system and [U]perldoc -f qx[/U for details.

Best wishes ... cheers, drl

Last edited by drl; 04-21-2012 at 01:47 PM..
# 3  
Old 04-21-2012
Hi WongSifu,

One way:
Code:
$ perl -ne 'if ( m/pattern/ ) { printf qq[%s\n], $ARGV; close ARGV; }' *

# 4  
Old 04-22-2012
Thanks guys,

But I'm not sure if this is going to help me. Let me explain my issue a bit more.

I have a list of values and a folder that contains more files than I want to loop through. The values are contained in only a couple of the files. That is why I wanted to use GREP to populate an array (with the files) that I could then loop through the files in the folder that I care about.

Will using "system" work like that?
# 5  
Old 04-23-2012
Hi.

Showing how system and grep perl functions work:
Code:
#!/usr/bin/env bash

# @(#) s2	Demonstrate command (not function) _grep_ from perl.

pe() { for _i;do printf "%s" "$_i";done; printf "\n"; }
pl() { pe;pe "-----" ;pe "$*"; }
db() { ( printf " db, ";for _i;do printf "%s" "$_i";done;printf "\n" ) >&2 ; }
db() { : ; }
C=$HOME/bin/context && [ -f $C ] && $C perl

pl " Files data{1,2,4}.txt have this content:"
cat data1.txt

pl " File data3.txt:"
cat data3.txt

pl " perl script p1:"
cat p1

pl " Results:"
./p1

exit 0

producing:
Code:
% ./s2

Environment: LC_ALL = C, LANG = C
(Versions displayed with local utility "version")
OS, ker|rel, machine: Linux, 2.6.26-2-amd64, x86_64
Distribution        : Debian GNU/Linux 5.0.8 (lenny) 
bash GNU bash 3.2.39
perl 5.10.0

-----
 Files data{1,2,4} have this content:
Now is the time
for all good men
to come to the aid
of their country.

-----
 File data3.txt:
Nothing to see here. Move along. Move along.

-----
 perl script p1:
#!/usr/bin/env perl

# @(#) p1	Demonstrate feature (minimal).

use strict;
use warnings;

my(@a);

print "\n";
print " Output directly from system to STDOUT:\n";
system('grep -l time *.txt');

print "\n";
@a = qx/grep -l time *.txt/;
print " List from qx:\n ", join(" ",@a), "\n";

exit 0;

-----
 Results:

 Output directly from system to STDOUT:
data1.txt
data2.txt
data4.txt

 List from qx:
 data1.txt
 data2.txt
 data4.txt

See perldoc perlop, searching for qx for more information.

Best wishes ... cheers, drl

( Edit 1: corrected error in perldoc advice. )

Last edited by drl; 04-23-2012 at 09:05 AM..
 
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. BSD

Searching in multiple files

I am new to unix and I would like to search multiple log files to find earliest occurrence of a text. Ex: Say I have 10 logs file each ending with .log and I want to find the text “CustomeError” . I want to find the which log file “CustomeError” comes first and lines which surround’s ... (4 Replies)
Discussion started by: jim john
4 Replies

2. Shell Programming and Scripting

Searching for multiple patters using grep

i have a file as below grepfile.txt ---------------- RNTO command successful No such file or directory Authentication failed if i seach individually for 'RNTO command successful' or 'No such file or directory' using grep -i as below, im gettting result. grep -i 'No such file or... (5 Replies)
Discussion started by: JSKOBS
5 Replies

3. UNIX for Dummies Questions & Answers

Grep - Searching for multiple items using one command

I am performing a regular check on UNIX servers which involves logging onto UNIX servers and using the grep command to check if a GID exists in the /etc/group directory e.g. grep 12345 /etc/group I have five to check on each server, is there anyway I can incorporate them into one command and... (2 Replies)
Discussion started by: @MeDaveT
2 Replies

4. Shell Programming and Scripting

searching multiple patterns in perl

Hi, I have code like: Output it is comming as: Rels: WM2 Rels: WG2 Rels: 5 - pre/prods.pl Rels: 6 Rels: 7 Rels: 8 Rels: 10 Rels: Int But i want only "Rels: 5" pattern Just above "- pre/prods.pl". By... (7 Replies)
Discussion started by: Anjan1
7 Replies

5. Shell Programming and Scripting

Searching across multiple files if pattern is available in all files searched

I have a list of pattern in a file, I want each of these pattern been searched from 4 files. I was wondering this can be done in SED / AWK. say my 4 files to be searched are > cat f1 abc/x(12) 1 abc/x 3 cde 2 zzz 3 fdf 4 > cat f2 fdf 4 cde 3 abc 2... (6 Replies)
Discussion started by: novice_man
6 Replies

6. Shell Programming and Scripting

Searching a word in multiple files

Hi All, I have a issue in pulling some heavy records , I have my input file has 10,000 records which i need to compare with daily appended log files from (sep 1st 2009 to till date) . I tried to use grep fgrep and even sed , but the as time is factor for me , i cannot wait for 5 days to get the... (3 Replies)
Discussion started by: rakesh_411
3 Replies

7. Shell Programming and Scripting

Perl, searching multiple files and printing returned line to new file

I am trying to find a way to utilise the full potential of my cpu cores and memory on my windows machine. Now, I am quite familiar with grep, however, running a Unix based OS is not an option right now. Unfortunately, the 32 bit grep for windows that I am running, I cannot run multiple... (1 Reply)
Discussion started by: Moloch
1 Replies

8. Shell Programming and Scripting

Searching for multiple patterns in files

I have a situation where I need to search for multiple strings (error messages) such as 'aborted' 'file not found' etc in directory having logs. I have put all the error messages in a text file and using the command. grep -f <textfile> <filetobegrepped> I'm doing this thru a script where I... (5 Replies)
Discussion started by: bornon2303
5 Replies

9. UNIX for Dummies Questions & Answers

Perl searching and printing multiple target in the same line

Hello, I'm trying to create a program in perl called myfind.pl; To use the program: (at the command line)$ program.pl keyword filename note: the keyword is any word or regular expression and it should display the result just like when you 'cat' the file name but with the keyword in... (2 Replies)
Discussion started by: Horizon666
2 Replies

10. Shell Programming and Scripting

Searching multiple files with multiple expressions

I am using a DEC ALPHA running Digital UNIX (formly DEC OSF/1) and ksh. I have a directory with hundreds of files that only share the extension .rpt. I would like to search that directory based on serial number and operation number and only files that meet both requirements to be printed out. I... (6 Replies)
Discussion started by: Anahka
6 Replies
Login or Register to Ask a Question