LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   Bash script to search through directories. (http://www.linuxquestions.org/questions/programming-9/bash-script-to-search-through-directories-553011/)

mcdrr 05-10-2007 08:12 PM

Bash script to search through directories.
 
Hello everyone I was wondering if someone could please give an example point me in the right direction on how I would go about scripting a search script using bash, I am new to Linux and scripting, I can do basic bash scripts and just need some example to start from as what I have tried so far does not work.

I have log directories in the following format and would like to search the logs for specific information looping through several days.

/log/device/year/month/day/
/log/device/2007/05/01
/log/device/2007/05/02..then about 5 different log files in each "day" directory which I would like to grep for certain data.

What I would like to do is start searching at the "month" directory then have the script loop through the each one of the "day" folders.

Here is one example I often have to search the logs spanning five or six day and have to manually cd into each directory and do a search for and IP, like so grep 10.10.10.1 *
So what I would like to be able to do is grep/run the script for 10.10.10.1 but over a span XX days. Not sure if I should use find or grep or another command to search the log files.

thanks for all the help in advance :)

chrism01 05-11-2007 02:32 AM

Roughly like this, depending on what you want to do when you get a match
Also, pass in start pt /log/device/2007/05 from an outer loop as a variable or cmd line param?
(find is recursive)
Code:

for file in `find /log/device/2007/05 -type f print 2>/dev/null`
do
    grep $pattern $file 1>dev/null 2>&1
    if [[ $? -eq 0 ]]
    then
        echo "$pattern found in $file"
    fi
done


bigearsbilly 05-11-2007 02:34 AM

firstly,
if you do a for dir in */
the slash will only pick up directories, useful but little known.

also you can do deep wild cards something like,

Code:

for dir in /log/device/05/*/*.log
do
  grep blah $dir
done


bigearsbilly 05-11-2007 02:35 AM

firstly,
if you do a for dir in */
the slash will only pick up directories, useful but little known.

also you can do deep wild cards something like,

Code:

for log in /log/device/05/*/*.log
do
  grep blah $log
done

or just

grep blah /log/device/05/*/*.log

archtoad6 05-11-2007 10:31 AM

Both good advice/approaches.

Thanks for the tip, billy.

mcdrr 05-11-2007 05:41 PM

Great thanks all for the replies I will give the examples a shot and post back.

thanks again guys!!!


All times are GMT -5. The time now is 12:30 PM.