Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

In a directory containing many files, if a particular regexp (or format) was found in file, I'd like to get that filename

Example:

  1. If the word "rama" is found in file called ramayana, print the filename "ramayana"

  2. if a file contains a particular format something like "(TEXT - NUMBERS)" in a file name called table, print that filename table in shell that was pretty easy,something like

    grep "mytext" * | cut -d':' -f1 | uniq

    but how to do it in perl

Suggestions on helpful CPAN modules are appreciated, too.

share|improve this question
add comment

1 Answer 1

up vote 3 down vote accepted

Maybe I miss a point, but if your original request is basically the same with this:

grep -l "mytext" *

Then its perl equivalent could be written as:

perl -ne 'if(/mytext/){print"$ARGV\n";close ARGV}' *

Note to readers: the following code is updated according to the owner comments, not fully compatible with the original question.

#!/usr/bin/perl

@list_code=qw{ over 100 elements here };
@original=@ARGV;

foreach $ele (@list_code) {
  @ARGV=@original;
  @found=();
  while (<>) {
    if (/\Q$ele\E/) {
      push @found,$ARGV;
      close ARGV;
    }
  }
  print "$ele found in ",scalar @found," files : \n",join "\n",@found,'';
}
share|improve this answer
    
Thanks for reply, can you help me how to use oneliners in perl program, it will help time. thanks again –  user1228191 Feb 24 '12 at 10:30
1  
I have an array @list_code that contains over 100 elements. when i am trying to search them like this foreach $ele (@list_code) { while (<>) { if (/\Q$ele\E/) { print "$ARGV\n"; close ARGV; } } } the prompt went to wait mode, which was slightly different, any idea!! –  user1228191 Feb 24 '12 at 11:26
    
But then, it will display all the filelist that array elements contain, which was not intended. To be more precise, the required output should be like, 1st array element is found in these many files and its filenames. 2nd array element is found in these many files and its filenames. 3rd array element .. and so on!! Hope this time i was clear in my question. –  user1228191 Feb 24 '12 at 12:56
    
Sir, ur awesomee!! thank you very much –  user1228191 Feb 24 '12 at 13:27
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.