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


  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.


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.


@list_code=qw{ over 100 elements here };

foreach $ele (@list_code) {
  while (<>) {
    if (/\Q$ele\E/) {
      push @found,$ARGV;
      close ARGV;
  print "$ele found in ",scalar @found," files : \n",join "\n",@found,'';
| 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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