Search code examples
windowsbatch-filebatch-processingfindstr

FINDSTR Result issue in Batch File


I want to search all files in a certain directory and print results in text file. But i want results in separated by '|' based on file name. Example. My Input files are A.txt and B.txt etc...

My Batch Script

@echo off
setlocal
pushd D:\Source
findstr  /c:"Apple" /c:"Banana" /c:"Grapes" *.txt > Results.txt
popd
endlocal

Results are coming like this

a.txt Apple
a.txt Banana
b.txt Banana
b.txt Grapes

But i want result like this

a.txt Apple|Banana
b.txt Banana|Grapes

HOW TO GET HELP!!


Solution

  • @ECHO OFF
    SETLOCAL enabledelayedexpansion
    SET "sourcedir=c:\sourcedir\abg"
    SET "resultfile=results.xtx"
    pushd %sourcedir%
    DEL %resultfile% 2>nul
    SET "filename="
    FOR /f "tokens=1*delims=:" %%r IN ('findstr  "Apple Banana Grapes" *.txt') do (
     IF "!filename!"=="%%r" (
      SET "line=!line!|%%s"
     ) ELSE (
       IF DEFINED filename >>%resultfile% ECHO(!filename! !line!
       SET "filename=%%r"
       SET "line=%%s"
     )
    )
    
    IF DEFINED filename >>%resultfile% ECHO(!filename! !line!
    
    TYPE %resultfile%
    
    popd
    
    GOTO :EOF
    

    I set up the destination filename as a variable in order to avoid the problem that the results.txt file may be included in the input processing, since it is created in the same directory as the data files.

    I also changed the directory name to suit my system.