2015-02-05 87 views
1
替换字符串

我试图找出如何使用VBScript来:
1 - 打开一个.csv文件为.txt文件
2 - 搜索的某些字符串文本随机位于整个文本中 3 - 用不同的字符串替换该字符串。查找和.txt文件使用VBScript

我发现了一篇文章,帮助我学习如何替换.txt文档中的整行,但到目前为止没有找到任何有关替换行中某些字符的运气。

谢谢!

这里是我使用当前的代码:

Const ForReading = 1 
Const ForWriting = 2 

'Setting up our objects and focusing on the text file. 
Set objFSO = CreateObject("Scripting.FileSystemObject") 
Set objFile = objFSO.OpenTextFile("C:\Users\Documents\Script Practice\TextFiles-2-4-15-Folder\ReadandWrite\Textlook.txt", ForReading) 


Do Until objFile.AtEndOfStream 

    strLine = objFile.ReadLine 


    If strLine = "Myer" Then 
     strLine = "Mike" 
    End If 

    strContents = strContents & strLine & vbCrLf 

Loop 



objFile.Close 


Set objFile = objFSO.OpenTextFile("C:\Users\Documents\Script Practice\TextFiles-2-4-15-Folder\ReadandWrite\Textlook.txt", ForWriting) 


objFile.Write(strContents) 
objFile.Close 

文本文件,它引用说:
根·迈尔
的Fabrikam

皮拉尔阿克曼
翼尖玩具

杰夫·海伊
Fabrikam

艾伦·亚当斯
罗斯文商贸

迈尔

(文本文件结束)。所以基本上,我已经得到了代码,成功地将自己的“Myer”更改为“Mike”。我很难与第一行中的“迈尔”改为“迈克”。希望这有助于澄清一些事情......我非常新,因此不太确定我应该用什么语言来描述问题。

+0

请证明您到目前为止已经尝试过的方法,并且有可能我们可以帮助您弄清楚您做错了什么。 – 2015-02-05 17:15:07

+0

我添加了一些编辑到我的问题,希望有所帮助。 – M199463 2015-02-05 21:15:40

回答

1

使用替换由.ReadAll()获取的文件内容并将结果写回。在代码:

Option Explicit 

Dim goFS : Set goFS = Createobject("Scripting.FileSystemObject") 
Dim goWAU : Set goWAU = WScript.Arguments.Unnamed 

WScript.Quit main() 

Function main() 
    main = 1 ' assume error 
    If 3 = goWAU.Count Then 
    If goFS.FileExists(goWAU(0)) Then 
     Dim s : s = goFS.OpenTextFile(goWAU(0)).ReadAll() 
     If 0 < Instr(s, goWAU(1)) Then 
      goFS.CreateTextFile(goWAU(0)).Write Replace(s, goWAU(1), goWAU(2)) 
      WScript.Echo "done" 
      main = 0 
     Else 
      WScript.Echo goWAU(1), "not found" 
     End If 
    Else 
     WScript.Echo goWAU(0), "does not exist" 
    End If 
    Else 
    WScript.Echo "need 3 args: fspec, find, replacement" 
    End If 
End Function 

输出:

copy con 28350055.csv 
1,2,3 
4,5,6 
^Z 

cscript 28350055.vbs 28350055.csv 5 4711 
done 

type 28350055.csv 
1,2,3 
4,4711,6 

cscript 28350055.vbs 28350055.csv 5 4711 
5 not found 

cscript 28350055.vbs 28350055.cs 5 4711 
28350055.cs does not exist 

使用演示,以确定什么是需要解决您的现实世界中的问题。