FINDSTR 在单个输出行中进行多重搜索(修订版 2)

FINDSTR multiple search in one single output line (Revision 2)

这是 FINDSTR 函数的第 2 版,用于搜索多个关键字并将它们输出到每个文件的一行中

文件#1 - CW_TESTDP3_9_13_0925.txt 包含以下

User: "DanMac"  
Date: "Wednesday April 05 2017"      Part#: "CW_EVALTCAPDP3_9_13_37"  
Time: "09:25:57 AM"         Operator: "CALVIN"

Unit; Voltage; Power; Host; Grb1; grn2;    
1; 220; 390; 24; 2; 5     
2; 234; 340; 64; 11; 15     
3; 10; 904; 2443; 211; 115     
4; 320; 390; 24; 2; 5     

Total_Test_time : 35minutes 40seconds

文件#2 - BW_ENGDP3_8_13_232345.txt 包含以下

User: "Jerry"  
Date: "Tuesday April 04 2017"      Part#: "BW_EENGDP3_9_13_37"  
Time: "10:15:57 AM"         Operator: "CALVIN"

Unit; Voltage; Power; Host; Grb1; grn2;    
1; 220; 390; 24; 2; 5     
2; 234; 340; 64; 11; 15    
3; 10; 904; 2443; 211; 115     
4; 320; 390; 24; 2; 5     
5; 24; 40; 4; 511; 154     
6; 103; 4; 2; 21; 125     
7; 345; 90; 4; 122; 53     

Total_Test_time : 45minutes 4seconds    

预期输出

c:\temp\CW_TESTDP3_9_13_0925.txt:User: "DanMac"; Date: "Wednesday April 05 2017"; Time: "09:25:57 AM"; Total_Test_time : 35minutes 40seconds
c:\temp\BW_ENGDP3_8_13_232345.txt:User: "Jerry"; Date: "Tuesday April 04 2017"; Time: "10:15:57 AM"; Total_Test_time : 45minutes 4seconds
@echo off
setlocal enabledelayedexpansion
for %%f in (??_*.txt) do (
  set "line="
  for /f tokens^=1^,2delims^=^" %%a in ('type "%%f" 2^>nul^|findstr "User: Date: Time: Total_Test_time"') do (
   set "line=!line!; %%a"%%b""
  )
  echo %%~ff:!line:~2,-1!
)
@ECHO Off
SETLOCAL enabledelayedexpansion 
SET "sourcedir=U:\sourcedir"
SET "destdir=U:\destdir"
SET "filename1=%sourcedir%\%1"
SET "outfile=%destdir%\%1"
SET "outline="
FOR /f "delims=" %%a IN ('findstr /b  "User: Date: Time: Total_Test_time" "%filename1%"') DO (
 FOR /f "tokens=1*delims=: " %%r IN ('echo %%a') DO (
  CALL :aparams %%s
  IF DEFINED parm2 (SET "outline=!outline!; %%r: "!parm1!""
   ) ELSE (
  SET "outline=!outline!; %%a"
  )
 )
)
>"%outfile%" ECHO %outline:~2%

GOTO :EOF

:aparams
SET "parm1=%~1"
IF "%~3"=="" (SET "parm2=") ELSE (SET "parm2=%~2")
GOTO :eof

您需要更改 sourcedirdestdir 的设置以适合您的情况。

运行 的预期语法:

thisbatchname filename

findstr命令过滤掉关键行。所选行被划分为任何冒号之前的部分或 space 到 %%r 以及第一组冒号和 space 到 %%s 之后的剩余部分。余数由过程 :aparams 分析,它将第一个保存在 parm1 中,将第二个保存在 parm2 中,但前提是存在第三个

这为连接输出提供了足够的信息,可以是 %%a 中的整个原始行,也可以是 %%r 中的初始字符串,': ' 和 :aparams 中保存的参数引号;每个都以 ;.

为前缀

组装好一行,输出,跳过g前2个字符(累加机制添加的开头;

@echo off
setlocal EnableDelayedExpansion

cd c:\temp
for /F "tokens=1* delims=:" %%a in ('findstr /I "User Date Time" *.txt') do (
   for /F tokens^=1-2delims^=^" %%c in ("%%b") do (
      set "file[%%a]=!file[%%a]!%%c"%%d"; "
   )
)
for /F "tokens=2 delims=[]" %%a in ('set file[') do echo %%~Fa:!file[%%a]:~0,-4!