Batch file to edit line in ini file

2019-05-06 20:56发布

问题:

I have an ini file that gets autogenerated.

Its second line is always: Version = W.XX.Y.ZZ

Where W is the major version number, XX is the minor version, Y is the Build and ZZ is the Revision.

I need to open that ini file and edit that line using a batch file so that the build and revision numbers in that version get removed. Therefore, the line should end up like this: Version = W.XX

The major number will always be one character and the minor number will always be two, therefore the entire string is 14 characters (inc spaces) long.

I was hoping that I could get the string that is LEFT 14 characters of that line and replace that line with that string.

回答1:

The "LEFT" syntax you're asking for is to use a variable substring expansion: %var:~,14%

The following code will perform a "LEFT 14" on every line that contains the string "Version"

setlocal enabledelayedexpansion
del output.ini
for /f "tokens=*" %%a in (input.ini) do (
  set var=%%a
  if not {!var!}=={!var:Version=!} set var=!var:~,14!
  echo.!var! >> output.ini
)
endlocal

If there are other lines with the word "Version", you can also modify the loop to use a counter.

setlocal enabledelayedexpansion
del output.ini
set counter=0
for /f "tokens=*" %%a in (input.ini) do (
  set var=%%a
  set /a counter=!counter!+1
  if !counter! EQU 2 set var=!var:~,14!
  echo.!var! >> output.ini
)
endlocal

Note that in both cases, you might have to do more work if your file contains special symbols like |, <, or >