Home > OS >  Bash - Find directory containing specific logs file
Bash - Find directory containing specific logs file

Time:10-08

I've created a script to quickly analyze some logs and automatically provide advices to solve problems based on errors found. All works as expected.

However, it's appears that folders structure containing these logs can change (depends on system configuration) and my script not work any more.

I would like to find a way to find the directory containing a specifics files like logs or appinfo.txt file.

Once obtains I could use it as variable and finally solve my problem.

Here is an example:

AppLogDirectory ='Your_Special_Command_You_Will_HelpMe_To_Find'
grep -i "Error" $AppLogDirectory/esl*.log 
  • Log format is: ESL.randomValue.log
  • Files analyzed : appinfo.txt, system.txt etc ..

A suggested in comment section, I edit my orginal post with more detail to clarify the context, below an example:

Log files (esl.xxx.tt.ss.log ) can be in random directory, like: 
/var/log/ApplicationName/logs/
/opt/ApplicationName/logs/
/var/data/ApplicationName/Extended/logs/

Because of random directory, I need to find a solution to print the directory names of the files that match esl*.log patter (without esl filename)

CodePudding user response:

Use find and pass the output to xargs with grep, like so, which runs grep on multiple files and prints the output together with the file name where the pattern was found:

find /path/to/files /another/path/to/other/files \( -name 'appinfo.txt' -o -name 'system.txt' -o -name 'esl*.log' \) -print0 | xargs -0 grep -i 'Error'

Or simply use -exec ... \ , which gives the same effect, without the need for xargs:

find /path/to/files /another/path/to/other/files \( -name 'appinfo.txt' -o -name 'system.txt' -o -name 'esl*.log' -exec grep -i 'Error' \ 

To find the directories which contain the files that contain the desired pattern, use grep -l to print file names only (not the lines that match), and pipe the results to xargs dirname to print the directory names. If you need the unique dir names, pipe it further to sort -u:

find /path/to/files /another/path/to/other/files \( -name 'appinfo.txt' -o -name 'system.txt' -o -name 'esl*.log' -exec grep -il 'Error' \  | xargs dirname | sort -u

SEE ALSO:
GNU find manual
To search for files based on their contents
xargs

CodePudding user response:

Solution found thanks to you thank you again!

#Ask for extracted tar.gz folder
    read -p "Where did you extract the tar.gz file? r1

#directory path where esl files is located
    logpath=`find $r1 -name "esl*.log" | xargs dirname | sort -u` 

#Search value (here "Error") into all esl*.log 
    grep 'Error' $logpath/esl*.log | awk '{print $8}'
  • Related