1

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));
 closedir(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 Jan 20 '17 at 5:30
  • I have a list of unknown directories – Maria Jan 20 '17 at 5:32
  • It's recursive, in your example somedir would be A. – jordanm Jan 20 '17 at 5:33
  • Ok how will I find the .txt file. Extract with grep i got that part, sort of confused – Maria Jan 20 '17 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 Jan 24 '17 at 3:56
2

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 Jan 20 '17 at 6:55
  • can you modify your post and let us know the directory structure and the expected output. so we can help – Kamaraj Jan 20 '17 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 Jan 20 '17 at 16:29
  • just use -h option in grep. it will ignore the file name. – Kamaraj Jan 24 '17 at 3:41

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.