findstr在一个输出行中进行多次搜索

时间:2017-04-05 06:13:26

标签: batch-file cmd findstr

我有多个文本文件,其中包含3行信息,我想将其作为每个文件的一行输出

实施例

File1.txt 包含

User: "John"
Date: "13-March-2017"
Time: "10.30am"
Remarks: "xcvsfas"

File2.txt 包含

User: "Mary"
Date: "13-March-2017"
Time: "11.30am"
Remarks: "xerteyas"

我的预期输出如下

c:\temp\file1.txt:User: "John"; Date: "13-March-2017"; Time: "10.30am"
c:\temp\file2.txt:User: "Mary"; Date: "13-March-2017"; Time: "11.30am"

我试过了 findstr /s /i "user date time:" %inputfolder%\*.* > %outputfolder%\final.txt

3 个答案:

答案 0 :(得分:1)

编辑:在其他答案的评论中发布的新规范修改的代码 :(

@echo off
setlocal EnableDelayedExpansion

set "file="
(
for /F "tokens=1* delims=:" %%a in ('findstr /S /I "user date time" %inputfolder%\*.*') do (
   if "!file!" neq "%%a" (
      if defined file echo !file!:!out!
      set "file=%%a"
      set "out=%%b"
   ) else (
      set "out=!out!; %%b"
   )
)
echo !file!:!out!
) > %outputfolder%\final.txt

答案 1 :(得分:0)

我假设你所有的.txt都在同一个文件夹中,只有它们。然后我得到每个文件的前三行,并使用set命令将它们打印成一行:

@echo off

setlocal EnableDelayedExpansion

pushd <files dir>
for /f %%i in ('dir /b') do (
    set "c=0"
    for /f "tokens=*" %%j in ('type "%%i"') do (
        set /a "c=c+1"
        if "!c!" equ "3" (
            set /p "=%%j" <nul
        ) else if "!c!" lss "3" (
            set /p "=%%j; "<nul
        )
    )
    echo(
)
popd

我测试了你给出的输入,结果是:

User: "John"; Date: "13-March-2017"; Time: "10.30am";
User: "Mary"; Date: "13-March-2017"; Time: "11.30am";

希望它有所帮助。

答案 2 :(得分:0)

您可以通过for循环遍历文件并单独进行搜索 - 如下所示:

@echo off
setlocal EnableExtensions DisableDelayedExpansion

rem // Define constants here:
set "_LOCATION=."
set "_INPUTFILES=File*.txt"
set "_OUTPUTFILE=%~dpn0.log"

rem // Write everything into output file:
> "%_OUTPUTFILE%" (
    rem // Iterate over matching files recursively:
    for /R "%_LOCATION%" %%F in ("%_INPUTFILES%") do (
        rem // Initialise line string variable:
        set "LINE=%%~F:"
        rem // Search currently iterated input file for the keywords:
        for /F "delims=" %%L in ('findstr /L /I /B "User: Date: Time:" "%%~F"') do (
            rem // Store found item:
            set "ITEM=%%L"
            rem // Toggle delayed expansion in order not to lose exclamation marks:
            setlocal EnableDelayedExpansion
            rem // Build line string and transfer result over `endlocal` barrier:
            for /F "delims=" %%E in ("!LINE!!ITEM!; ") do (
                endlocal
                set "LINE=%%E"
            )
        )
        rem // Return built line string:
        setlocal EnableDelayedExpansion
        echo !LINE:~,-2!
        endlocal
    )
)

endlocal
exit /B

字段User:Date:Time:按照它们在每个文件中显示的原始顺序返回。