LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   How to do "grep" on each file in directory (https://www.linuxquestions.org/questions/programming-9/how-to-do-grep-on-each-file-in-directory-818290/)

grob115 07-06-2010 11:25 AM

How to do "grep" on each file in directory
 
Hello,

Can someone show me how I can do the following in a bash script?
1) Load all *.log files into an array variable
2) Iterate through the array, and do a "grep" on each of the file to see if it contains a "word".

Sergei Steshenko 07-06-2010 11:35 AM

Quote:

Originally Posted by grob115 (Post 4025273)
Hello,

Can someone show me how I can do the following in a bash script?
1) Load all *.log files into an array variable
2) Iterate through the array, and do a "grep" on each of the file to see if it contains a "word".

Why not simply

grep PATTERN *.log

?

grail 07-06-2010 06:32 PM

I am with Sergei, I feel you are over thinking your solution.

syg00 07-06-2010 08:42 PM

C'mon guys, bash now supports associative arrays - wouldn't be too difficult to do ....:p

jschiwal 07-06-2010 09:46 PM

This sounds like a homework question. If you want further help, you should post what you have tried. Look in the bashref manual and read through section 6.7 for information about using array variables.

grob115 07-07-2010 04:34 AM

No this is not a homework question. Unfortunately I can't recall the reason why I was thinking of doing it this way. I have moved on to other projects, and will need to re-visit this at another time. Will post here what I've tried previously.


However, I think it's because of the reason I want to see what it had grepped on what file. So I think I've echoed the file name first, with `grep <word> $filename[count]` ...... Can't remember the exact syntax. But the grep result overwrites part of the echoed file name.

Sergei Steshenko 07-07-2010 04:37 AM

Quote:

Originally Posted by grob115 (Post 4026025)
...
However, I think it's because of the reason I want to see what it had grepped on what file. So I think I've echoed the file name first, with `grep <word> $filename[count]` ...... Can't remember the exact syntax. But the grep result overwrites part of the echoed file name.

(Re)read 'man grep' - 'grep' has a command line switch allowing to see the file in which a match occurs.

Sergei Steshenko 07-07-2010 04:39 AM

And consider 'find' with '-exec'.

rkelsen 07-07-2010 05:16 AM

grep -r "word" /directory

- or -

for i in `ls /directory`; do grep "word" $i; done


All times are GMT -5. The time now is 07:30 AM.