Reputation: 149
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!!
Upvotes: 0
Views: 602
Reputation: 79982
@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.
Upvotes: 1
Reputation: 67196
@echo off
setlocal EnableDelayedExpansion
cd D:\Source
set "filename="
for /F "tokens=1* delims=:" %%a in (
'findstr "Apple Banana Grapes" *.txt') do (
if not defined filename (
set /P "=%%a %%b" < NUL
set "filename=%%a"
) else if "!filename!" equ "%%a" (
set /P "=|%%b"
) else (
echo/
set /P "=%%a %%b" < NUL
set "filename=%%a"
)
)
echo/
Some notes on previous code:
endlocal
command at end is not necessary.pushd
command and a popd
at end may be replaced by setlocal
followed by cd
at beginning and nothing at end.findstr
command you may define several strings to search separating they with space.Upvotes: 1