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

Answers


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


@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.
  • In findstr command you may define several strings to search separating they with space.

Need Your Help

Optimizing "IS NULL"

optimization sql-server-2008-r2

I have a query that is very slow due to a IS NULL check in the where clause. At least, that's what it looks like. The query needs over a minute to complete.