Batch file to search for string in most recent file

1.1k views Asked by At

I have alot of log files which need searching for certain strings and was wondering if I could make a batch file to automate this job for me? All I need it to do is locate the most recent log in a certain directory then search for the string in that file.

I have found the below code on this website which works great to open the most recent log file but unfortunatly I dont know enough about batch programming to amend the code to search for the string and display the line.

for /f "usebackq delims=" %%i in (`dir /b /o-d`) do @call "%%i"&goto :eof

Any help would be much appreciated.

2

There are 2 answers

0
André Pires On

At first, set which is the file you want. If /od doesn't work, try /o-d...

for /f %%i in ('dir \path\to\files\ /b /od') do set myfile=%%i

... and pay attention because myfile will come without pathway.

Then use for /f "tokens=*" to read each line of the file fully, and findstr to search for your STRING...

for /f "tokens=*" %%i in (\path\to\files\%myfile%) do (echo %%i | findstr STRING >> OUTPUTFILE)

If you want OUTPUTFILE to be overwritten everytime you run the code, use a single >.

If you don´t want a file, but see the output on screen, just delete the >> OUTPUTFILE code.

0
Preet Sangha On

Add a findstr to the end:

or /f "usebackq delims=" %%i in (`dir /b /o-d`) do findstr searchforthisstring %%i

What this is doing is searching for "searchforthisstring" the files found by

dir /b/o-d 

Which list files (/b = simply name not any other info and /o-d reverse date order