Sheldon Murray
Sheldon Murray

Reputation: 25

Batch issue with FIND command

I'm trying to get a test code working so I can make a more complex version of the script for my actual needs, but I'm struggling with the FIND command.

My code:

@echo off
SETLOCAL DISABLEDELAYEDEXPANSION

>"%~dpn1_b.txt" (
  FOR /F "tokens=1* delims=]" %%j in ('find /V /N "" %1') DO (
    SET "currentLine=%%k"
    SETLOCAL ENABLEDELAYEDEXPANSION
    IF "!currentLine:~0,3!"=="12/" (
      SET string=!currentLine:~0,2!!currentLine:~3,4!
      FIND "%string%" 111.txt > nul
      IF %errorlevel% EQU 0 (SET "currentLine=!currentLine:~0,2!!currentLine:~3!")
    )
    ECHO(!currentline!
    ENDLOCAL
  )
)

This is executed by dragging test.txt onto the batch file.

111.txt holds 123456. test.txt has 12/3456 on the first line and 12/4456 on the second line. The script is supposed to remove the slash from the first line but not from the second. Any idea what went wrong?

Upvotes: 0

Views: 90

Answers (2)

Stephan
Stephan

Reputation: 56180

interesting: you get the line numbers (%%j) but then don't use it...

How about:

...
if "%%j"=="[1" (
  ...
) else (
  echo %%k
)
...

Upvotes: 0

wardies
wardies

Reputation: 1259

Within the FOR loop body, all environment variable expansions using the %var% format will be pre-expanded. You still need to use the delayed expansion !var! format even for internal variables like errorlevel.

FOR /F ... (
    ...
    FIND "!string!" 111.txt > nul
    IF !errorlevel! EQU 0 (SET "currentLine=!currentLine:~0,2!!currentLine:~3!")
)

As Ryan mentioned, this is clearer if you leave ECHO enabled as you see that with the original code the last two statements in the loop were being pre-expanded:

FIND "" 111.txt 1>nul

IF 0 EQU 0 (SET "currentLine=!currentLine:~0,2!!currentLine:~3!" )

Upvotes: 1

Related Questions