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