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

时间:2017-04-10 08:33:55

标签: batch-file cmd findstr

这是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

3 个答案:

答案 0 :(得分:0)

@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!
)

答案 1 :(得分:0)

@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命令过滤掉关键行。选定的那些行被划分为%%r的任何冒号或空格之前的部分以及第一组冒号和空格之后的行的其余部分%%s。其余部分由:aparams程序进行分析,该程序将第一个保存在parm1中,第二个保存在parm2中,但仅限于第3个。

这提供了足够的信息来连接输出,%%a中的整个原始行或%%r中的初始字符串,':'以及:aparams在引号中保存的参数;每个都以;为前缀。

组装完线后,输出它,跳过前2个字符(由累积机制添加的初始;

答案 2 :(得分:0)

@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!