Adnan Haq
Adnan Haq

Reputation: 1

How to use findstr within a loop?

I am trying to read the filename and according to the filename set the Output variable.

I have tried using findstr directly on %%F (findstr /i "M002" %%F >nul 2>&1 ) and also writing to a temp text file (as below) to test and read it, but nothing worked.

What I'm doing wrong?

P.S. If I remove this out from the loop the code works, but I need it within the loop due to the last line.

rem ===========================================

set FileType=pdf

for %%F in (%~dp0*.%FileType%) do (
  rem ECHO %%F

  echo "%%F" > test.txt
  findstr /i "M002" test.txt >nul 2>&1
  echo %errorlevel%
  if not %errorlevel% == 0 (
      echo "4pp"
      echo %%F
      set Output=4PP
  ) ELSE (
      echo "Letter"
      echo %%F
      set Output=Letter
  )

  set NetComm="XYZ" "%Output%" etc etc etc
)

rem ====================================

Upvotes: 0

Views: 3100

Answers (1)

Magoo
Magoo

Reputation: 80023

Generation 5,961 of delayedexpansion.

Batch parses the entire statement from the for through to the last closing parenthesis and replaces any %var% with the value of that variable at the time the statement is parsed.

Consequently, attempting to use a value which is established within the loop will fail. This applies to %output% and %errorlevel% in the current instance.

Dealing with %errorlevel% is easy. The syntax

if errorlevel n

works on the run-time value of errorlevel and is true if errorlevel has been set to n or greater than n.

Personally, I find the if not condition ... else clumsy. I can't see why it's so common. Fuzzy thinking in my book...

There are three common ways to overcome the problem, each has its own advantages and disadvantages, proponents and critics.

First, the "documented" method. Use a setlocal enabledelayedexpansion instruction. Once this instruction has been executed, !var! will access the current value and %var% the initialvalue ofvar`.

Second, the subroutine method. CALL :sub within a loop executes a subroutine (see the documentation - call /? from the prompt) and within that subroutine, %var% will have the value as established within the loop.

Third, it's sometimes possible to use call echo %%var%% (or call someotherinsruction) where the call is executiong the target as if it was a subroutine.

Hence, in your case, a fix might be

rem ===========================================

set FileType=pdf

for %%F in (%~dp0*.%FileType%) do (
  rem ECHO %%F

  findstr /i "M002" "%%F" >nul 2>nul
  CALL echo %%errorlevel%%
  if errorlevel 1 (
      echo "4pp"
      echo %%F
      set Output=4PP
  ) ELSE (
      echo "Letter"
      echo %%F
      set Output=Letter
  )

  CALL set NetComm="XYZ" "%%Output%%" etc etc etc
)

rem ====================================

depending entirely on your definition of "works" (which is not an absolute - it has meaning only to you.)

Upvotes: 1

Related Questions