2012-02-09 71 views
0

比方說,我有一個包含下列文件:更改文本行

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

真的,什麼設置,我不知道我在工作的批處理文件的唯一我知道的事情肯定是「set_t lorem」部分。

但我需要更換任何值它(在set_t LOREM 168即)與即100

我將如何做到這一點的一個批處理文件? Vbs或外部二進制文件可以;雖然不是很多依賴關係會很好。它需要大規模分發。

回答

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 
+0

你能否讓它到的東西,我可以通過命令行參數使用它呢?如:cscript // nologo script.vbs「file.txt」「set_t lorem」「100」? – 2012-02-09 10:27:43

+0

答覆已更新。祝你好運。 – 2012-02-09 12:28:31

+0

感謝您的編輯,完美工作! – 2012-02-09 12:34:58