windowsbatch-filecmddelayedvariableexpansion

Windows command working in cmd but not .bat file


I am trying to replace a line in certain files (based on file extension). The program is not working as desired, and the command which is causing issue is the one below.

FOR /F %%k IN ('TYPE !FILE! ^| FINDSTR /N "^"') DO (

This comes back with following error:

FINDSTR: No search strings The process tried to write to a nonexistent pipe.

However, the command itself works as expected when run in command line. I have already spent nearly 1 full day but to no avail. FOR /F %k IN ('TYPE <filename> ^| FINDSTR /N "^"') DO echo(%k

Pointers will be greatly appreciated!

Complete code is provided below for reference.

@echo off
CD data
FOR /F "delims=" %%i IN ('DIR *.ext1 /B') DO (
  SET "FILE=%%i"
  SETLOCAL EnableDelayedExpansion
  echo(!FILE!
  <!FILE! >!FILE!.tmp~ (
    REM Find line number on which Logon command is found
    FOR /F "tokens=1,* delims=: " %%j IN ('FINDSTR /I /N /R "^\.LOGON.*" !FILE!') DO (
      SET "NUM=%%j"
    )
    REM Print all lines along with line number at beginning
    FOR /F %%k IN ('TYPE !FILE! ^| FINDSTR /N "^"') DO (
      SET "LINE=%%k"
      REM Replace entire content of Logon line with Run file command
      FOR /F "tokens=1,* delims=:" %%l IN ("!LINE!") DO IF %%l EQU !NUM! (
        echo(.RUN FILE logon.txt;
      ) ELSE (
        echo(!LINE:*:=!
      )
    )
  )
  MOVE /Y "!FILE!.tmp~" !%FILE!"
  ENDLOCAL
)
CD ..

Solution

  • As long as your source run files don't have any lines which begin with a : character, the following may provide an alternative method of performing the task:
    @%__AppDir__%where.exe /Q "data":"*.mload" >NUL 2>&1 && (CD "data"
        For /F "EOL=? Delims=" %%H In (
            '%__AppDir__%findstr.exe /IM "\<\.LOGON\>" "*.mload" 2^>NUL'
        ) Do @(Copy /Y "%%H" "%%~nH.tmp~" >NUL && (
                    For /F "Tokens=1,* Delims=:" %%I In (
                        '%__AppDir__%findstr.exe /N "^" "%%~nH.tmp~"'
                    ) Do @Set /P "=:%%J"<NUL|%__AppDir__%findstr.exe /LIB ":.LOGON " >NUL && (
                            Echo .RUN FILE logon.txt;) || Echo=%%J)>"%%H"
            Del "%%~nH.tmp~" 2>NUL))
    

    Just to be clear, my reading of your requirement is to, replace all lines inside all .mload files within .\data, which begin with the case insensitive string .LOGON , with the line .RUN FILE logon.txt;