Reputation: 3
I need to edit some configuration file by appending new line to existing file, but not at the end of the file but somewhere in the middle instead (at the end of particular section)
# section 1 description
foo1 = bar1
foo2 = bar2
# section 2 description
foo3 = c:\bar.cfg
my_new_line = which_needs_to_be_appended_here
# section 3 description
foo4 = bar4
Should I use search and replace like described here:
to find last line of particular section and replace it with: itself + new line character + my_new_line = which_needs_to_be_appended?
OR
maybe there is a simpler or more clever method to do same thing (like finding the last line of particular section and use some method to put my new line right AFTER it)?
Upvotes: 0
Views: 11009
Reputation: 38745
As your task is to append a line to a section and your data seems to indicate that sections are separated by two line endings, using Split() on that separator looks like a good strategy that doesn't rely on knowing the last key-value-pair of that section:
Dim sAll : sAll = readAllFromFile("..\data\cfg00.txt")
WScript.Echo sAll
Dim aSects : aSects = Split(sAll, vbCrLf & vbCrLf)
aSects(1) = aSects(1) & vbCrLf & "fooA = added"
sAll = Join(aSects, vbCrLf & vbCrLf)
WScript.Echo "-----------------------"
WScript.Echo sAll
output:
=========================
# section 1 description
foo1 = bar1
foo2 = bar2
# section 2 description
foo3 = c:\bar.cfg
# section 3 description
foo4 = bar4
-----------------------
# section 1 description
foo1 = bar1
foo2 = bar2
# section 2 description
foo3 = c:\bar.cfg
fooA = added
# section 3 description
foo4 = bar4
=========================
Upvotes: 2