需要为 ms-dos 应用程序找到命令解决方案吗?

Need find command solution for ms-dos application?

我有一些 *.bat 文件,其中包含 find 命令以提取特定行。

例如,如果我的输入文本文件包含如下内容:

Login time : XX:XX
username - XXXXXX
Login time : YY:YY
username - YYYYYYY

使用用户名以免说:

find /I "XXXXXX" input.txt | find /I "XXXXXX" > output.txt

我可以获取用户名,但不确定如何只为搜索到的用户名获取正确的登录时间?

find(和 findstr)无法处理换行。他们自己处理每一行。因此,您必须编写一个脚本来记住最后一行,检查搜索字符串的当前行,如果找到搜索字符串,则打印最后一行和当前行。

我使用 findstr 而不是 find,因为它更安全(find "XXXXXX" 也会找到 XXXXXXY)。请参阅 findstr /? 以了解开关 ixc

@echo off
setlocal enabledelayedexpansion
set "search=xxxxxx"

for /f "delims=" %%a in (t.txt) do (
  echo %%a|findstr /ixc:"username - %search%" >nul && echo !lastline! %%a
  set "lastline=%%a"
)

假设您实际上正在处理 (cmd.exe) rather than on (COMMAND.COM), you could use findstr,它允许定义一个 multi-line 搜索字符串,虽然它只是 returns 匹配的第一行,但是下一行一个总是一样的,所以可能不需要。

这个Windows说明了我的意思:

@echo off
rem // Get Carriage-Return (CR) character:
for /F %%C in ('copy /Z "%~f0" nul') do set "CR=%%C"
rem // Get Line-Feed (LF) character:
(set LF=^
%= blank line =%
)
rem // Enable delayed expansion to be able to use CR and LF:
setlocal EnableDelayedExpansion
rem /* Specify a multi-line search string, which must literally reflect the actual
rem    line-break (that is CR + LF for a DOS/Windows text file); `findstr` returns
rem    only the first line when it encounters a match: */
findstr /I /R /C:"!CR!!LF!username - XXXXXX$" "input.txt" > "output.txt"
rem /* This is needed to get the second line of the multi-line match too
rem    (replace this by the commented out line in case you expect multiple entries for
rem    the searched user, because you would get multiple equal user name entries; the
rem    commented out line ensures that there is a single user name entry at the end): */
findstr /I /R /C:"^username - XXXXXX$" "input.txt" >> "output.txt"
rem findstr /I /R /C:"^username - XXXXXX$" "input.txt" | findstr /I /R /V /C:"!CR!!LF!username" >> "output.txt"

N。 B.:
我猜你正在使用两个 find 命令来摆脱第一个产生的 header;但是,您可以改用以下内容:

rem // Input redirection `<` prevents `find` from returning a header:
find /I "XXXXXX" < "input.txt" > "output.txt"