1

I create a simple batch to replace a specific string in a file and dump the output to a new file:

set oldstring=SERVER_IP
set newstring=10.10.10.1

setlocal enabledelayedexpansion
for /f "tokens=*" %%i in (test.txt) do (
     set str=%%i
     set str=!str:%oldstring%=%newstring%!
     echo !str!>>newfile
 )

If I run it on a file containing caracter 'a' a line feed, then a white space and a line feed I get the wrong output.

a[lf]
 [lf]

OUPUT:

a
SERVER_IP=10.10.10.1

Why do I get this the string I'm trying to replace in the output whenever I have a line full of white spaces?

EDIT

Expected output

a
code-gijoe
  • 6,949
  • 14
  • 67
  • 103

1 Answers1

1

This happens, as %%i is empty for a line with white spaces.
str is also empty and empty variables are not defined.

To replace an empty variable fails, everything before the colon is dropped.

The line set str=!str:%oldstring%=%newstring%! will be evaluated to set str=SERVER_IP=10.10.10.1!.
The exclamation mark will be dropped due the delayed expansion, that's all.

You can check if str is defined.

....
if defined str (
    set str=!str:%oldstring%=%newstring%!
    echo(!str!>>newfile
)
jeb
  • 78,592
  • 17
  • 171
  • 225
  • I moved the output echo inside the IF so we don't get a "echo is off" message. But this worked very well. – code-gijoe Mar 01 '16 at 18:05
  • Therefore I used `echo(!str!`. The parenthesis is important here, it avoids problems with empty strings and any other possible content in `!str!` like `ON`, `OFF` or `/?` – jeb Mar 01 '16 at 20:05