0

我需要通过将新行附加到现有文件来编辑一些配置文件,但不是在文件的末尾,而是在中间的某个地方(在特定部分的末尾)

# 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

我应该像这里描述的那样使用搜索和替换:

http://blogs.technet.com/b/heyscriptingguy/archive/2005/02/08/how-can-i-find-and-replace-text-in-a-text-file.aspx

找到特定部分的最后一行并将其替换为:自身 + 换行符 + my_new_line = which_needs_to_be_appended?

或者

也许有一种更简单或更聪明的方法来做同样的事情(比如找到特定部分的最后一行并使用某种方法将我的新行放在它之后)?

4

1 回答 1

2

由于您的任务是将一行附加到一个部分,并且您的数据似乎表明部分由两个行尾分隔,因此在该分隔符上使用 Split() 看起来是一个不依赖于知道最后一个键值的好策略-该部分的对:

  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

输出:

=========================
# 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

=========================
于 2012-04-08T18:41:26.450 回答