我想搜索特定的单词,然后在每一行我想添加的单词之后;在开始
问题描述:
使用下面的代码我能够在每行的开头添加;
,但是我想在找到特定单词后添加;
,例如, [Abc]
。如何使用VBScript来做到这一点?我想搜索特定的单词,然后在每一行我想添加的单词之后;在开始
Const ForReading=1
Const ForWriting=2
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set f = objFSO.OpenTextFile("D:\sam.txt", ForReading)
Do Until f.AtEndOfStream
strText = f.ReadLine
If Len(strText) = 0 Then
blnFound = True
MsgBox "blank line found"
strText = vbNewLine & strText
strContents = strContents & strText & vbCrlf
Else
strText = ";" & strText
strContents = strContents & strText & vbCrlf
End If
Loop
f.Close
Set f = objFSO.OpenTextFile("D:\sam.txt", Forwriting)
f.WriteLine strContents
f.Close
Sam.txt
包含一些行,例如,
Hi, need help This is a sample text file [Abc] How are you Hope you are doing well!
所以我想输出sam.txt
文件应该有下面的数据里面:
Hi, need help This is a sample text file [Abc] ;How are you ;Hope you are doing well!
答
所以,基本上,你有一个INI风格文件,并希望在一个特定部分的条目评论。可以实现这样的:
filename = "D:\sam.txt"
Set fso = CreateObject("Scripting.FileSystemObject")
txt = Split(fso.OpenTextFile(filename).ReadAll, vbNewLine)
disable = False
For i = 0 To UBound(txt)
If Left(txt(i), 1) = "[" Then
If txt(i) = "[Abc]" Then
disable = True
Else
disable = False
End If
End If
If disable Then txt(i) = ";" & txt(i)
Next
fso.OpenTextFile(filename, 2).Write Join(txt, vbNewLine)
答
试试这个
Option Explicit
Dim FSO ' Object
Set FSO = CreateObject("Scripting.FileSystemObject")
Dim ReadTxtFile, WriteTxtFile ' Object
Dim TextLine, TextLineToWrite ' String
Dim AddStr' bool
' Open both text file in the same time
Set ReadTextFile = FSO.OpenTextFile("Sam.txt", 1) ' Open file to read
Set WriteTextFile = FSO.OpenTextFile("Sam_new.txt", 2, True) ' Open file to write
' Do read file as normal but add a switch
' Write original text line to text file while switch is disabled
' Add str to the text line and write once switch is trigger
AddStr = False ' Add str disabled
Do Until ReadTextFile.AtEndOfStream ' Start Read
Textline = ReadTextFile.Readline
If AddStr = True Then ' If add str enabled
TextLineToWrite = ";" & Textline ' Add string
Else ' if add str disabled
TextLineToWrite = Textline ' write original line
End If
If Trim(Textline) = "[ABC]" Then ' If indicator read
AddStr = True ' add str write
End if
WriteTextFile.WriteLine TextLineToWrite ' Write file when each line is read
Loop
ReadTextFile.Close
WriteTextFile.Close
msgbox "Done"
+0
'设置WriteTextFile = FSO.WriteTextFile( ......)'??? –
+0
对不起,假设是'Set WriteTextFile = FSO.OpenTextFile(...)'并且将Dim StartWrite改为Dim AddStr –
取代它; 'strText =替换(strText,“[Abc]”,“[Abc];”)' –
谢谢你回复我的帖子,但我想要下面的输出。 Sam.txt是含有某些行e.g 嗨,需要帮助 这是一个示例文本文件 [ABC] 你怎么 希望你做得很好! 所以我想输出sam.txt文件应具有以下里面的数据: - 嗨,需要帮助 这是一个简单的文本文件 [ABC] ;你怎么样 ,希望你做得很好! – sam