Linux: Grep Script to Search Multiple Directories

Audience that may find this useful will mostly be new Linux administrators.ascii art for Grep

This is a Command Line Interface (CLI) Shell script that once set up using the directories you want to search.  All you will have to do is enter the word or phrase that you are trying to search and it will search across the directories (if you use *) and files for the key word/phrase.

In the past, I have used it to search dozens of logs in production at the same time for errors.

#!/bin/bash### First add the directories you want to search
locationAlpha=”/LOGS/Websphere-01/General.log”
locationBravo=”/LOGS/Websphere-02/General.log”
locationCharlie=”/LOGS/Websphere-03/General.log”
locationDelta=”/LOGS/Websphere-04/General.log”
locationEcho=”/LOGS/Websphere-05/General.log”
locationFoxtrot=”/LOGS/Websphere-06General.log”
locationGulf=”/LOGS/Websphere-07/General.log”### Next line will prompt for the word or phrase you want to search
read -p “Enter the word you want to find: ” word
 
## returns word you entered
echo “Searching for ‘$word'”
 
##Starts searching and returning hits
grep -iH “$word” $locationAlpha $locationBravo $locationCharlie $locationDelta $locationEcho $locationFoxtrot $locationGulf

–>                                               View file here without comments–> countProd.txt

Initially called countProd.sh because I was using it to count the number of certain errors. If you would like to only count the number of error. Change “grep -iH” to “grep -ic” (c for count, H to return filename for each match, and i to ignore case) . 

That’s it, short and simple.

About Adam M. Erickson

Geek, Dad, Life-Student, Biker & DIY Enthusiast Application Developer Attended Ferris State University Lives in Muskegon, MI
Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.