Find the latest file and search for string

2019-09-19 12:54发布

I have list of text files in a folder, I want to:

  1. Find the latest file in the folder

  2. In the latest file, find the string = "Error"

  3. Copy the whole row with string = "Error"

  4. 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

3条回答
地球回转人心会变
2楼-- · 2019-09-19 13:32

Other answers already show how to find the latest (last modified) file in a directory (dir, for /F):

set "string=Error"
set "log_path=C:\path\Log"

for /F "delims= eol=|" %%F in ('
    dir /B /A:-D /O:D "%log_path%\*.*"
') do (
    set "latest=%%F"
)

findstr /I /R /C:"\<%string%\>" "%log_path%\%latest%"

The findstr command line returns all lines that contain the word Error 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 string Errors 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:

findstr /I /R /C:"\<%string%\>" "%log_path%\%latest%" > "error_log.txt"
查看更多
兄弟一词,经得起流年.
3楼-- · 2019-09-19 13:44
...
FOR /F "delims=" %%I IN ('DIR %log_path%*.* /A:-D /O:-D /B') do (
 findstr /I /L /C:"%string%" "%log_path%%%I" 
 goto done
)
echo none found!
:done

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 the dir 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 \.

查看更多
ゆ 、 Hurt°
4楼-- · 2019-09-19 13:54

it's a bit easier that you think. (and your if logic doesn't work at all)

FOR /F "delims=" %%I IN ('DIR %log_path%\*.* /A:-D /O:D /B') do set "LATEST=%%~fI"
findstr /I /R /C:"%string%" "%LATEST%" 
查看更多
登录 后发表回答