面对使用vbscript替换文件中的字符串的问题

时间:2014-12-09 12:25:14

标签: vbscript

我有一个包含以下数据的文本文件

mkdir language

这是我的vbscript,用于替换文本文件中的语言字符串

Const ForReading = 1
Const ForWriting = 2

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\Scripts\Text.txt", ForReading)

strText = objFile.ReadAll
objFile.Close
strNewText = Replace(strText, "language", "english,french,spanish")

Set objFile = objFSO.OpenTextFile("C:\Scripts\Text.txt", ForWriting)
objFile.WriteLine strNewText
objFile.Close

我正在输出mkdir英语,法语,西班牙语,但我想在文本文件中输出如下所示

mkdir english
mkdir french
mkdir spanish

如何实现这一点请帮助

3 个答案:

答案 0 :(得分:0)

尝试此变体:

Const ForReading = 1
Const ForWriting = 2

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\Scripts\Text.txt", ForReading)

strText = objFile.ReadAll
objFile.Close
Set objFile = objFSO.OpenTextFile("C:\Scripts\Text.txt", ForWriting)

For Each strLanguage In Array("english", "french", "spanish")
    objFile.WriteLine Replace(strText, "language", strLanguage)
Next

objFile.Close

答案 1 :(得分:0)

使用Join从数组构建字符串:

>> c = "mkdir "
>> l = Split("english,french,spanish", ",")
>> WScript.Echo c & Join(l, vbCrLf & c)
>>
mkdir english
mkdir french
mkdir spanish

当然,c可能来自文件。

(但我怀疑你的真实世界问题没有在你的简化样本中显示)

答案 2 :(得分:0)

这也会起作用......

Const ForReading = 1
Const ForWriting = 2

Dim langs
langs = Array("english","french","spanish")

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("Text.txt", ForReading)

strText = objFile.ReadAll
objFile.Close
tempTxt = ""
strNewText = ""
For Each i in langs
    tempTxt = "mkdir " + i + vbCrLf
    strNewText = strNewText + tempTxt
Next

strNewText = Replace(strText, "mkdir language", strNewText)

Set objFile = objFSO.OpenTextFile("Text.txt", ForWriting)
objFile.WriteLine strNewText
objFile.Close