查找最新文件并搜索字符串 [英] Find the latest file and search for string

查看:73
本文介绍了查找最新文件并搜索字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在一个文件夹中列出文本文件,

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

  1. 在文件夹中查找最新文件

  1. Find the latest file in the folder

在最新文件中,找到字符串="Error"

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

使用字符串="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

推荐答案

其他答案已经显示了如何在目录( for /F ):

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%"

findstr命令行以不区分大小写的方式返回所有包含单词Error的行(/I).搜索字符串中的\<\>表示单词边界,因此搜索字符串必须是单个单词,因此字符串Errors不构成匹配项.仅当完成正则表达式搜索(/R)时此方法才起作用,这意味着您必须转义某些元字符,例如.*^$[]\在您的搜索字符串中,并在前面加上\来进行逐字处理.
如果要Errors构成匹配项,请删除/R或将其替换为/L强制进行文字搜索.

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.

如果要将findstr的输出写入文件,请使用重定向:

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"

这篇关于查找最新文件并搜索字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆