Gosh, forget about batch for parsing files , even for anything!. It only has very primitive string manipulation capabilities, does not do decimal maths, has ugly syntax making maintenance and debugging difficult, slow to execute etc.
If you can't use a good programming language, use the next best thing that comes with modern Windows, vbscript (or powershell).
Code: Select all
Set objFS = CreateObject( "Scripting.FileSystemObject" )
strFile = WScript.Arguments(0)
Set objFile = objFS.OpenTextFile(strFile)
contents = objFile.ReadAll
Data = Split(contents,vbCrLf&vbCrLf)
For i=LBound(Data) To UBound(Data)
flag = 0
WScript.Echo "->"&Data(i)
d = Split( Data(i) , vbCrLf )
For j=LBound(d) To UBound(d)
WScript.Echo "==>"&d(j)
If InStr( d(j) , "section2" )> 0 Then
'set flag when found section2
flag = 1
End If
index = InStr( d(j), "xyz=" )
If index > 0 And flag = 1 Then
WScript.Echo "Found key before replacement: " & d(j)
d(j) = Mid(d(j), 1, Len("xyz=") )
WScript.Echo "After replacement: " & d(j)
Exit For
End If
Next
Data(i) = Join(d, vbcrlf)
Next
Data = Join(Data, vbCrLf&vbCrLf )
WScript.Echo "===================="
WScript.Echo "Final: " &Data
output
Code: Select all
C:\test>type file
; Comment
[section1]
abc=000
xyz=123
[section2]
def=000
xyz=234
C:\test>cscript //nologo test.vbs file
->; Comment
==>; Comment
->[section1]
abc=000
xyz=123
==>[section1]
==>abc=000
==>xyz=123
->[section2]
def=000
xyz=234
==>[section2]
==>def=000
==>xyz=234
Found key before replacement: xyz=234
After replacement: xyz=
====================
Final: ; Comment
[section1]
abc=000
xyz=123
[section2]
def=000
xyz=
I show the output using arrows. First of all, the script reads the whole ini file into memory. Then it splits the whole content on 2 new lines , that is, assuming your ini file has the structure as shown. The small arrow "->" shows each section being split. Next, the script splits again on 1 new line to give you the individual lines in each section. These are shown with "==>" arrows... Now, you can begin searching for your "xyz=" in "section2". When the script finds "section2" , a flag is set to 1. If "xyz=" is found and the flag is 1, that means the "xyz=" belongs to "section2" and you can do the replacement.
If you need to save to a file, use the ">" redirection
Code: Select all
cscript //nologo test.vbs file > temp
ren temp file
This method does not need to read the file multiple times ( i counted more than 8 times in the batch solution! ) using findstr , more blah blah as illustrated by aGerman's long and complicated batch file (no offense to aGerman ), hence, will be much faster than the batch solution, plus, easier to maintain and troubleshoot. If you are interested, get a copy of the vbscript manual
here