2015-02-05 41 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 

使用演示,以確定什麼是需要解決您的現實世界中的問題。