如何使用 Visual Basic 在多个文件中查找和替换文本字符串 [英] How to find and replace text strings in multiple files using Visual Basic
问题描述
我有一个关于简单 vbs 脚本的基本问题.我的目标是在多个文件中找到替换多个文本字符串.(要替换的 21 个文本字符串在不同文件中是相同的.)文件名有大约 12 个前缀,然后在末尾有数字 1 到 200.我仅用于其中一个文件中的一个字符串的基本代码如下.
I have a basic question about a simple vbs script. My goal is to find a replace multiple text strings in multiple files. (The 21 text strings to replace are the same across files.) The file names have about 12 prefixes and then will have numbers 1 to 200 at the end. The basic code I am using for just one of the strings in one of the files is as follows.
Const ForReading = 1
Const ForWriting = 2
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\filename_XX.txt", ForReading)
strText = objFile.ReadAll
objFile.Close
strNewText = Replace(strText, "Test 1", "Test 2")
Set objFile = objFSO.OpenTextFile("C:\filename_XX.txt", ForWriting)
objFile.Write strNewText
objFile.Close
我只想遍历文件名并可能遍历搜索字符串.For...Next 循环可以完成这个吗?我可以参考文件名对象中for循环的编号吗?
I just want to loop over the file names and possibly loop over the search strings. Could a For...Next loop accomplish this? Can I refer to the number of the for loop in the filename object?
我看到了一个关于搜索子文件夹的回复,但我认为它比我需要做的更复杂.
I have seen a response about searching over subfolders, but I think it is more sophisticated than what I need to do.
推荐答案
如果文件都在同一个目录中并且文件名都类似于 prefix_##.txt
,你可以这样做:
If the files are in the same directory and all have a filename like prefix_##.txt
you could do something like this:
Set fso = CreateObject("Scripting.FileSystemObject")
Set prefixes = CreateObject("Scripting.Dictionary")
prefixes.CompareMode = vbTextCompare 'make dictionary lookups case-insensitive
prefixes.Add "prefix1", True
prefixes.Add "prefix2", True
'...
For Each f In fso.GetFolder("C:\basefolder").Files
If InStr(f.Name, "_") > 0 Then
If prefixes.Exists(Split(f.Name, "_")(0)) Then
text = fso.OpenTextFile(f.FullName).ReadAll
text = Replace(text, "Test 1", "Test 2")
fso.OpenTextFile(f.FullName, 2).Write text
End If
End If
Next
如果你想使用文件名的数字部分,你必须从文件名中提取它,例如像这样:
If you want to use the number part of the file name, you have to extract it from the file name, e.g. like this:
num = Split(fso.GetBaseName(f.Name), "_")(1)
如果您的文件不在同一目录中,则需要递归到子文件夹中.此外,如果您有类似 prefix_##somethingelse.txt
或 prefix_##.otherextension
的文件名,则必须添加进一步的检查以将它们排除在处理之外.
If your files are not all in the same directory you'll need to recurse into subfolders. Also, if you have file names like prefix_##somethingelse.txt
or prefix_##.otherextension
, you'll have to add further checks to exclude them from processing.
这篇关于如何使用 Visual Basic 在多个文件中查找和替换文本字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!