在Windows批处理中更改文件中的文本行

时间:2012-02-09 09:59:44

标签: windows batch-file

假设我有一个包含以下内容的文件:

set_t lorem = "168"
set_t ipsum = "913"
set_t dolor = "294"
...

真的,设置的是什么,我在批处理文件中无法知道。我唯一知道的就是“set_t lorem”部分。

但是我需要用它来取代它所拥有的任何值(即在set_t lorem中为168)。

我如何在批处理文件中执行此操作? Vbs或外部二进制文件都可以;虽然不是很多依赖会很好。它需要大规模分发。

1 个答案:

答案 0 :(得分:1)

这是一个VBScript解决方案:

Option Explicit

Const ForReading = 1
Const ForWriting = 2

Dim filename, prefix, newvalue, fso, file, str, line
Set fso = CreateObject("Scripting.FileSystemObject")

' Read and validate the parameters
If Not WScript.Arguments.Count = 3 Then
  Wscript.Echo "Syntax: PatchData FileName Prefix NewValue"
  Wscript.Quit 1
End If
filename = Wscript.Arguments(0)
prefix = Wscript.Arguments(1)
newvalue = Wscript.Arguments(2)
If Not fso.FileExists(filename) Then
  Wscript.Echo "Filename does not exists " & filename
  Wscript.Quit 1
End If

' Read the file 1 line at a time into a string, patching as we go
str = ""
Set file = fso.OpenTextFile(filename, ForReading)
While not file.AtEndOfStream
  line = file.ReadLine
  If Left(line, Len(prefix)) = prefix Then
    line = prefix & " = """ & newvalue & """"
  End If
  str = str & line & vbCrLf
Wend
Set file = Nothing

' Write the patched string back to the file
Set file = fso.OpenTextFile(filename, ForWriting)
file.Write str
Set file = Nothing