I am new to perl and I am trying to create a perl script (or bash script) which can extract the word "Hello World" from files with .txt extension in multiple directories. To make it more clear, suppose my script is placed in the directory "/home/pi/A" which has sub directories - Folder, Temp, Document (Directories are unknown to me it is just an example). The directory /home/pi/A/Folder has a .txt file and /home/pi/Temp has also have a .txt file so on.. Here is my code

 #!/usr/bin/perl -w

 opendir(DIR, ".");
 @files = grep(/\.txt$/,readdir(DIR));

 foreach $file (@files) {
    print "$file\n";

The output should be

Hello World  
Hello World
Hello World
So on... 
  • grep -r 'hello world' somedir
    – jordanm
    Commented Jan 20, 2017 at 5:30
  • I have a list of unknown directories
    – Maria
    Commented Jan 20, 2017 at 5:32
  • It's recursive, in your example somedir would be A.
    – jordanm
    Commented Jan 20, 2017 at 5:33
  • Ok how will I find the .txt file. Extract with grep i got that part, sort of confused
    – Maria
    Commented Jan 20, 2017 at 5:37
  • for specific files, grep --include='*.txt' -r 'Hello World' /path/to/dir ... use -i for case-insensitive search, -F if search term is not regex, would be faster
    – Sundeep
    Commented Jan 24, 2017 at 3:56

1 Answer 1


It will find the .txt file from a directory A and check whether it has the word "hello world"

find A -type f -name "*.txt" -exec grep -h "hello world" {} +
  • thanks, but I am getting the directory along with whole text in the txt file not only "hello world"
    – Maria
    Commented Jan 20, 2017 at 6:55
  • can you modify your post and let us know the directory structure and the expected output. so we can help
    – Kamaraj
    Commented Jan 20, 2017 at 8:22
  • Ok i have updated it, but /home/pi/A/ also consist of other 14 folders which contain txt files. It hard to show all 17 folders. Also I tried your code but I am getting path then the result. I just want the result ,thanks
    – Maria
    Commented Jan 20, 2017 at 16:29
  • just use -h option in grep. it will ignore the file name.
    – Kamaraj
    Commented Jan 24, 2017 at 3:41

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .