-1

I've created a simple batch file that searches in files with extension .opr and .eng for the term @DLOG_ETS and replace it with @DLOG_ETS=OFF. This may be redundant for cases where the full string is @DLOG_ETS=OFF.

I want to add the condition that only if the string @DLOG_ETS=ON is present, then I want to replace that with @DLOG_ETS=OFF. Otherwise, I want to leave it as it is, i.e. @DLOG_ETS=OFF without making any changes on those .opr or .eng files.

for %%F in (*.opr  *.eng) do (
    type "%%F"| findstr /v @DLOG_ETS= >"%%F.new"
    @echo @DLOG_ETS=OFF  >> "%%F.new"
    move /y "%%F.new" "%%F"
)
Mofi
  • 46,139
  • 17
  • 80
  • 143

2 Answers2

2
@ECHO Off
SETLOCAL
for %%F in (*.opr  *.eng) do (
 findstr /v /L "@DLOG_ETS=ON" "%%F" >"%%F.new"
 fc "%%F" "%%F.new" >nul
 IF ERRORLEVEL 1 (
  echo @DLOG_ETS=OFF>>"%%F.new"
  move "%%F.new" "%%F"
 ) ELSE (
  DEL "%%F.new"
 )
)

GOTO :EOF

For each file, create a new file, removing the line containing the target string. Compare the before and after versions. If there is a difference therefore the string was removed, so append the required line. If no difference, simply delete the new file.

Magoo
  • 77,302
  • 8
  • 62
  • 84
  • It works but @DLOG_ETS=OFF is always on the last line. That was the weakness of my earlier coding. Is there a way in which I can directly replace the string @DLOG_ETS=ON with the string @DLOG_ETS=OFF directly without having to move it to the last line? – MacGyver Dec 18 '16 at 00:50
  • This can be done, within limits, in pure batch if certain conditions are met, viz. you don't want to preserve empty lines and no line commences `;` (even these can be overcome.) If that is what you wanted to do, you should specify it as it changes the approach. The above routine will produce the same output as your original routine, with the benefit of not overwriting the original file for no-change. An easier approach would be to use `sed` (Google) and substitute `sed -s/@DLOG_ETS=ON/@DLOG_ETS=OFF/g "%%F" >"%%F.new" for the `findstr` line in the code above. – Magoo Dec 18 '16 at 06:09
0

Batch isn't predestined to do text file editing.
A lot of poison chars have to be circumvented.
Vbscript /jscript/PowerShell are all better suited to this task.

Here a batch which calls a sub to get help with Powershell. You need do adapt the path to your environment.

@Echo off
PushD "X:\Path\to\your\folder"
Set "Srch=@DLOG_ETS=ON"
Set "Repl=@DLOG_ETS=OFF"
Set "Opt=-nologo -noprofile -command"
for %%F in (*.opr *.eng
) do findstr /I "%Srch%" "%%~fF" >NUL 2>&1 && Call :PoSh "%%~fF"
PopD
Goto :Eof
:PoSh
PowerShell %Opt% "& {(GC %1).replace('%Srch%','%Repl%')|Set-Content %1}"
  • Thank you very much. Solution by Magoo really works but I have several errors with the second solution even by pointing to the right path. – MacGyver Dec 18 '16 at 00:46