Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
157 views
in Technique[技术] by (71.8m points)

cmd - Find the latest file and search for string

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:pathLog
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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
...
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 .


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...