如何替换txt文件中的文字和符号?

How to replace text and symbols in a txt file?

我有一个 web.config 文件,要更改设置,我必须手动进入并不断更改代码。

到目前为止我发现的是我正在尝试改编的示例脚本:

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

strText = objFile.ReadAll
objFile.Close
strNewText = Replace(strText, "Jim ", "James ")

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

我遇到的问题是我需要更改符号而不是文本,我认为这是搞砸了。

所以上面说JamesJim的地方,我的数据要改:

"<component type="Satsuma.Connectivity.Services.Contracts.Mocks.CallCredit.CallCreditCallValidateServiceProxyMock, Satsuma.Connectivity.Services.Contracts.Mocks" service="Satsuma.Connectivity.Services.Contracts.CallCredit.ICallCreditCallValidateService, Satsuma.Connectivity.Services.Contracts" /> ",

对此:

"<!--<component type="Satsuma.Connectivity.Services.Contracts.Mocks.CallCredit.CallCreditCallValidateServiceProxyMock, Satsuma.Connectivity.Services.Contracts.Mocks" service="Satsuma.Connectivity.Services.Contracts.CallCredit.ICallCreditCallValidateService, Satsuma.Connectivity.Services.Contracts" />-->",)

反之亦然。如果您看,只有开始和结束符号(例如 <!--<>-->)需要编辑。

可以像这样完成一个简单的字符串替换(出于可读性原因缩写了广泛的属性值):

srch = "<component type=""Sats...ocks"" service=""Sats...acts"" />"
repl = "<!--" & srch & "-->"
strNewText = Replace(strText, srch, repl)

请注意,VBScript 字符串中的嵌套双引号必须加倍以对它们进行转义。未转义的双引号会过早终止字符串,您很可能会遇到语法错误。

话虽如此,用字符串替换修改 web.config 文件是一个坏主意™,因为它们是 XML 文件,而在 XML 中,两者之间没有区别以下符号:

<component type="foo" service="bar" />

<component    type='foo'    service='bar'    />

<component
  type="foo"
  service="bar"
/>

<component type="foo" service="bar"></component>

你真正想做的是使用 XML parser. Something like this should do (code shamelessly stolen from this answer):

config = "C:\path\to\your\web.config"

Set xml = CreateObject("Msxml2.DOMDocument.6.0")
xml.async = False
xml.load config

If xml.parseError <> 0 Then
  WScript.Echo xml.parseError.reason
  WScript.Quit 1
End If

Set node = xml.selectSingleNode("//component[@type='Sats...ocks']")
Set comment = xml.createComment(node.xml)
node.parentNode.replaceChild(comment, node)

xml.save config

所有"inner"双引号应该""doubled""如下:

replWhat = "<component type=""Satsuma..Mocks"" service=""Satsuma..Contracts"" />"
'                           ^               ^          ^                   ^
replWith = "<!--" & replWhat & "-->" 

strNewText = Replace(strText, replWhat, replWith, 1, -1, vbTextCompare)

'and vice versa'
strOldText = Replace(strNewText, replWith, replWhat, 1, -1, vbTextCompare)

给定示例中的文本已缩短,以使命令保持合理的宽度以提高可读性。

阅读 VBScript Language Reference 以了解 Replace 函数的附加 , 1, -1, vbTextCompare 参数的含义。