batch file to search all .txt files in folder for string then copy 1st instance to output file.txt

Martin picture Martin · Jan 23, 2013 · Viewed 7.4k times · Source

I have about 100 plus .txt files with long file names in a folder, and I need to search the files for the 1st instance of the string "4096" and return the whole line from each file and copy it to an output .txt file.

I am a novice at batch syntax so a whole solution would be awesome,

thanks in advance.

Answer

Bali C picture Bali C · Jan 23, 2013

Here you go:

@echo off
setlocal enabledelayedexpansion
for %%a in (*.txt) do (
   set found=false
   for /f "skip=2 tokens=*" %%b in ('find "4096" "%%a"') do (
      if "!found!"=="false" (
         echo %%b >>output.txt
         set found=true
      )
   )
)