Aleksandr Kravets
Aleksandr Kravets

Reputation: 5947

BAT-file: FOR %%x variable incorrect expansion

I have bat-script with following code:

FOR /F "tokens=1,2 delims==" %%g in ("%CFGFILE%") do (
  SET firstChar=%%g
  SET firstChar=!firstChar:~1,1!
  if /I "!firstChar!"=="#" (
    echo %%g>>"%INSTALL_PATH%\tmp.cfg"
  )else (
    if /I "%%g"=="document.folder" (
      SET path_written=TRUE
      echo %%g=%DOC_FOLDER%>>"%INSTALL_PATH%\tmp.cfg"
    )else (
      rem next line is buggy
      echo %%g=%%h>>"%INSTALL_PATH%\tmp.cfg"
    )
  )
)

The point is parsing cfg-file %CFGFILE% contents and copying every string without changes to new config-file, except only one string starting with "document.folder". This line must be changed. Problem is that the line after "next line is buggy" comment gives "c:\program files\myApp\original.cfg=" which is content of %CFGFILE% variable plus equals sign. Is this a bug or i've done something wrong? Is this connected with %%x variables visibility?

Upvotes: 0

Views: 707

Answers (2)

jameslr
jameslr

Reputation: 51

My suggestion:

Use FART... http://sourceforge.net/projects/fart-it/

Upvotes: 0

dbenham
dbenham

Reputation: 130879

You have mis-identified the source of the problem! :-)

Your problem is in the very first line - your FOR statement is processing a string, not a file, because the IN() clause is enclosed by double quotes. If you want the IN() clause to be treated as a quoted file name, then you need to add USEBACKQ to your FOR options.

FOR /F "usebackq tokens=1,2 delims==" %%g in ("%CFGFILE%") do (

Just a heads up - even after the fix above, your code will not give the correct results if any of the following conditions appear

  • If any line contains ! then expansion of %%g or %%h will be corrupted because delayed expansion is enabled

  • Commented # line will be incomplete if the original contained =

  • Your normal lines will not be complete if there is a 2nd = in the original

Upvotes: 2

Related Questions