I have list of text files in a folder, I want to:
Find the latest file in the folder
In the latest file, find the string = "Error"
Copy the whole row with string = "Error"
If there are more than 1 Error found, copy as it as well
Script below very simple, I am very new to batch script, can help me to correct to make it work?
set today=%date:~10,4%%date:~4,2%%date:~7,2%
set today_day=%date:~7,2%
set today_year=%date:~10,4%
set today_month=%date:~4,2%
set log_path=C:\path\Log\
set string=Error
FOR /F "delims=" %%I IN ('DIR %log_path%\*.* /A:-D /O:-D /B') do set LATEST=%%I
If findstr /I /R /C:"%string%" %%I Do
Echo Copy the Error Message row
Else exit
Other answers already show how to find the latest (last modified) file in a directory (
dir
,for /F
):The
findstr
command line returns all lines that contain the wordError
in a case-insensitive manner (/I
). The\<
and\>
in the search string denote word boundaries, so the search string must be a single word, so the stringErrors
does not constitute a match. This works only if regular expression search (/R
) is done, which implies that you have to escape certain meta-characters like.
,*
,^
,$
,[
,]
and\
in your search string by preceding with\
to be treated literally.If you want
Errors
to constitute a match, remove/R
or replace it by/L
to force literal search.If you want to write the output of
findstr
to a file, use redirection:The
dir
yields the file NAMES only in reverse-date order, so the first file is the latest as required. This name is assigned to%%I
The
findstr
will then locate the required string, as a LITERAL (/L
) within the file; name needs to be assembled from the directory as the/B
switch on thedir
command supplies name only. Put in quotes to allow the target path to contain separators.Personally, I omit the closing
\
from pathnames and insert them where required. Since you've included the terminal\
in the variable, your code would string together two\
.it's a bit easier that you think. (and your
if
logic doesn't work at all)