我正在尝试查找可以在日志文件的行中查找特定文本的命令或批处理文件。找到文本后,我想在找到的文本之前包含前3行。我看到一些使用FOR循环的例子,但我只能得到一个令牌,而不是前面的行。有没有办法在没有批处理文件中的实用程序的情况下执行此操作?
@echo off
svn log https://sub.mycompany.com/svn/company-dev/ > c:\temp\svn.txt
setlocal EnableDelayedExpansion
rem Assemble the list of line numbers
set JiraID=%1
set numbers=
for /F "delims=:" %%a in ('findstr /I /N /C:"%JiraID%" c:\temp\svn.txt')
do (
set /A beforeo=%%a, before=%%a-1, before2=%%a-2
set "numbers=!numbers!: !beforeo!: !before!: !before2!:"
)
rem Search for the lines
(for /F "tokens=1* delims=:" %%a in ('findstr /N "^" c:\temp\svn.txt ^|
findstr /B "%numbers%"') do echo %%b)
del c:\temp\svn.txt
如果有办法与SVN LOG命令内联,我实际上不想转储SVN日志。创建的文件在输出到文本时会有空格
正在读取的输出在行之间也有空格,输出有时不包括“-----”行,因此尝试收集正确的行很棘手。有什么想法吗?
------------------------------------------------------------------------
r132279 | USERID | 2014-04-30 12:59:09 -0700 (Wed, 30 Apr 2014) | 3 lines
Removed unused "Calculated Fields" column entry.
Jira ID: JIRA-977
------------------------------------------------------------------------
答案 0 :(得分:2)
无需FOR / F循环。 FINDSTR具有未记录的跨换行符搜索功能,因此单个FINDSTR命令可以执行此操作!有关详细信息,请参阅What are the undocumented features and limitations of the Windows FINDSTR command?。
@echo off
setlocal enableDelayedExpansion
:: Define LF to contain a line feed character (0x0A)
set ^"LF=^
^" The above empty line is critical - DO NOT REMOVE
:: Define CR to contain a carriage return character (0x0D)
for /f %%A in ('copy /Z "%~dpf0" nul') do set "CR=%%A"
:: Define the string to search for
set "s=something"
findstr /r /c:"!s!" /c:"!lf!.*!s!" /c:"!lf!.*!cr!*!lf!.*!s!" /c:"!lf!.*!cr!*!lf!.*!cr!*!lf!.*!s!" test.txt
由于上述搜索使用正则表达式,因此必须对搜索字符串中的任何元字符进行转义。例如,搜索字符串中的句点将表示为\.
更新以响应已修改的问题
没有必要将原始文件保存到临时文件 - 它可以直接传送到FINDSTR。
@echo off
setlocal enableDelayedExpansion
:: Define LF to contain a line feed character (0x0A)
set ^"LF=^
^" The above empty line is critical - DO NOT REMOVE
:: Define CR to contain a carriage return character (0x0D)
for /f %%A in ('copy /Z "%~dpf0" nul') do set "CR=%%A"
:: Define the string to search for
set "s=%~1"
svn log https://sub.mycompany.com/svn/company-dev/|findstr /ri /c:"!s!" /c:"!lf!.*!s!" /c:"!lf!.*!cr!*!lf!.*!s!" /c:"!lf!.*!cr!*!lf!.*!cr!*!lf!.*!s!"
答案 1 :(得分:0)
(问题前的答案被编辑)
这可能就是你要找的东西:
@echo off
setlocal enabledelayedexpansion
set l1=
set l2=
set l3=
set findme=test
for /f %%l in (t.txt) do (
if "%%l"=="%findme%" echo.!l1! & echo.!l2! & echo.!l3!
set l1=!l2!
set l2=!l3!
set l3=%%l
)
将findme
设置为您想要的值。