Patrick
Patrick

Reputation: 123

batch script search for string in directory and save results to file

I've done a bit of searching and can't find anything that will do quite what I need, and my code isn't working for some reason.

I have a folder containing multiple subdirectories with log files, kind of like this;

  1. Day 1 Logs
    • Log Machine 1
    • Log Machine 2
    • Log Machine 3
  2. Day 2 Logs
    • Log Machine 1
    • Log Machine 2
    • Log Machine 3

and so on...

The script I'm writing is supposed to go into each subdirectory, search for a string in each file within that directory, and output the number of occurrences to a file within that directory

Expected result:

  1. Day 1 Logs
    • Log Machine 1
    • Log Machine 2
    • Log Machine 3
    • RESULTS
  2. Day 2 Logs
    • Log Machine 1
    • Log Machine 2
    • Log Machine 3
    • RESULTS

Then I have a script that goes through and zips up each folder as it's own zip file, for archiving purposes.

Here's the code I have:

ECHO /// UNZIPPING ALL FOLDERS AND DELETING ORIGINAL ZIPS ///
FOR /R "C:\Users\xxx\Desktop\LogQueue" %%I in ("*.zip") do (
   "%ProgramFiles%\7-Zip\7z.exe" x -y -o"%%~dpnI" "%%~fI" 
)
del /s /q /f C:\Users\pat\Desktop\LogQueue\*.zip

ECHO /// SEARCHING FOR STRING AND SAVING TO EXPORT FILE ///
cd "C:\Users\pat\Desktop\LogQueue"    
for %%f in (*.log) do findstr /i /m /p /c:"error" "%%f" >> results.txt


ECHO /// ZIPPING EVERYTHING BACK UP ///
for /d %%X in (*) do "c:\Program Files\7-Zip\7z.exe" a "%%X_new.zip" "%%X\" 

Any help appreciated. For whatever reason, the search function does absolutely nothing. The unzip and re-zip process works fine.

Upvotes: 2

Views: 2843

Answers (1)

sambul35
sambul35

Reputation: 1098

Save this script to analyze.bat, run from Cmd Prompt, try debugging any errors. Let me know, if need help:

@echo off
set dir=%USERPROFILE%\Desktop\LogQueue
echo /// UNZIPPING ALL FOLDERS AND DELETING ORIGINAL ZIPS ///
for /R "%dir%" %%I in ("*.zip") do (
   "%ProgramFiles%\7-Zip\7z.exe" x -y -o"%%~dpnI" "%%~fI" 
    del /s /q /f %%I )
echo /// SEARCHING FOR STRING AND SAVING TO EXPORT FILE ///
for /R "%dir%" %%G in (.) do (
    pushd "%%G"
    for %%H in (*.log) do find /i "error" "%%H" >> results.txt
    echo /// ZIPPING %%G folder ///
    for %%X in (*.*) do "c:\Program Files\7-Zip\7z.exe" a "%%X_new.zip" "%%G\"
    popd )
echo/& echo Completed
timeout 5
exit /b

Upvotes: 3

Related Questions