0
我在一個文件夾中有一堆txt文件,我需要爲每個文件添加一行到指定行號。VBS腳本,在多個文本文件中添加一個新行
input box 1 : New lineofText as string. input box 2 : Line where I want this lineoftext to be inserted, as an integer.
所有我發現是添加文本的頂部或底部,像這樣:
Dim FSO, txs, fld, fil, content
newline = inputbox("New line :")
line = inputbox("Which line :")
Set FSO = CreateObject("Scripting.FileSystemObject")
Set fld = FSO.GetFolder("\folderpath")
For Each fil In fld.Files
If Right(fil.Name, 3) = "txt" Then
Set txs = fil.OpenAsTextStream(1) ' 1 = for reading
content = txs.ReadAll
txs.Close
Set txs = fil.OpenAsTextStream(2) ' 2 = for writing
txs.Write newline & vbCrLf & content
txs.Close
End If
Next
寫到最後,我簡單地切換這樣的:
txs.Write newline & vbCrLf & content
這樣:
txs.Write content & vbCrLf & newline
但是,如何讓它將新行寫入指定的行號?
編輯:用戶哥們告訴我,我需要這方面的計算行:
Dim nLineToAddTheNewLine : nLineToAddTheNewLine = 5 ' your desired line where you need the new line
line = 5
newline = "blablabla"
filename = "C:\myfile.txt"
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(filename)
Dim nCount : nCount = 0
Dim sContent : sContent = ""
Do Until f.AtEndOfStream
WScript.Echo f.ReadLine
sContent = sContent & f.ReadLine
nCount = nCount + 1
If nCount = line Then sContent = sContent & vbCrLf & newline
Loop
f.Close
此代碼是爲一個文件,直名字。 所以在這一點上,我的腳本工作很困難。 這裏是我堅持:
Const ForReading = 1
Const ForWriting = 2
'newline = inputbox("New line :")
'line = inputbox("Which line :")
newline = "blablabla"
line = 6
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objRegEx = CreateObject("VBScript.RegExp")
objRegEx.Pattern = "Agent-API Blocking Queue Size: [1-9]+[0-9]*"
objStartFolder = "C:\MyfolderWithLotOfFiles\"
Dim lineCount : lineCount = 0
Dim firstContent : firstContent = ""
Set objFolder = objFSO.GetFolder(objStartFolder)
Set colFiles = objFolder.Files
For Each objFile in colFiles
lineCount = 0
firstContent = ""
FileName = objStartFolder & objFile.Name
WScript.echo FileName
Set objStream = objFSO.OpenTextFile(FileName, ForReading)
Do Until objStream.AtEndOfStream
lineCount = lineCount + 1
firstContent = firstContent & objStream.ReadLine
if lineCount = line Then
Set objStream = objFSO.OpenTextFile(FileName, ForWriting)
objStream.Write firstContent & vbCrLf & newline & vbCrLf
End if
Loop
objStream.Close
Next
腳本讀取每一個txt文件中的每一行,但是當我想寫,請幫助我得到了一個錯誤!
if lineCount = line Then
Set objStream = objFSO.OpenTextFile(FileName, ForWriting)
objStream.Write firstContent & vbCrLf & newline & vbCrLf
End if
在你的情況,我想,你應該閱讀線,並將它們存儲您的文本文件中的行到一個數組,然後瀏覽他們通過爲一個循環下一個 – Hackoo
在您上次的編輯中,您忘記了這一行==> Const ForWriting = 2 – Hackoo
是的,謝謝,我剛剛編輯了第一篇文章,duDE在幾個小時前回答,但它被刪除。問題是,我對vbs相當陌生,並且沒有像程序員那樣快速地獲得這個,我感到可恥,已經6個小時,我正在使用一個簡單的txt寫腳本。如果你能在最後幾行指出我的錯誤,那真的會很有意思嗎? –