Bipario
Bipario

Reputation: 221

nested findstr for text files in bat file

I have the following bat code to find a character in a set of text files and insert a new line after the found line:

for  /R "%SrcFolder%"  %%a in ("*.txt") do (
  (for /f "usebackq delims=" %%h in ("%%a") do (
    echo %%h
    echo "%%h"|findstr /I "{" > nul & if not errorlevel 1 (
        echo NEW LINE
     )
)

Now I want to employ another findstr to check if the previous line of the current line (%%h)had a specific character (such as "B") and if it does, skip inserting the new line.

I hope I could ask it clearly. Any suggestion ? Thanks.

Upvotes: 0

Views: 758

Answers (3)

Magoo
Magoo

Reputation: 80213

@ECHO OFF
SETLOCAL
SET "srcfolder=.\cb4c"

for /R "%SrcFolder%" %%a in ("*.txt") do (
 SET "checkme=Y"
 for /f "usebackq delims=" %%h in ("%%a") do (
  echo %%h
  IF DEFINED checkme (
   echo "%%h"|findstr /I "{" > NUL
   if not errorlevel 1 (echo NEW LINE)
  )
  echo "%%h"|findstr "B" > NUL
  if errorlevel 1 (SET "checkme=Y") ELSE (SET "checkme=")
 )
)
GOTO :EOF

(I've left my test setting for srcfolder in place)

Upvotes: 0

Aacini
Aacini

Reputation: 67296

The Batch code below do what you want:

@echo off
setlocal EnableDelayedExpansion

for /R "%SrcFolder%" %%a in ("*.txt") do (
   echo File: "%%a"
   set "prevLine="
   for /f "usebackq delims=" %%h in ("%%a") do (
      echo %%h
      rem Check if current line have "{" char:
      set thisLine=%%h
      if "!thisLine:{=!" neq "!thisLine!" (
         rem YES: Check if previous line have "B" char:
         if "!prevLine:B=!" equ "!prevLine!" (
            rem NO: insert the new line
            echo NEW LINE
         )
      )
      set "prevLine=!thisLine!"
   )
   echo -------------------
   echo/
)

However, this method does not use findstr, sorry...

findstr.exe is an external command that requires to load a ~30 KB file each time it is executed. If you execute findstr with each line of a file and sometimes two times, the program will run slower than if you use just internal commands. If a file is large, or the number of files is large, the difference between the two methods will be very noticeable...

Upvotes: 1

Endoro
Endoro

Reputation: 37589

try this:

@ECHO OFF &SETLOCAL disableDelayedExpansion
SET "InFileName=infile.txt"
SET "OutFileName=outfile.txt"
(FOR /f "delims=" %%a IN ('FINDSTR /n "^" "%InFileName%"') DO (
    SET "PrimLine=%%a"
    SETLOCAL enableDelayedExpansion
    SET "Line=!PrimLine:*:=!"
    ECHO(!Line!
    ECHO("!Line!"|FINDSTR "}" >nul && (
        SET "SecLine=!SecLine:*:=!"
        ECHO("!SecLine!"|FINDSTR /i "B" >nul || ECHO(
    )
    ENDLOCAL
    SET "SecLine=%%a"
))>"%OutFileName%"

Upvotes: 0

Related Questions