插入“-&引用;在特定位置使用VBScript

插入“-&引用;在特定位置使用VBScript,vbscript,insert,vbs,Vbscript,Insert,Vbs,我有一个文件有多行 要求每行第8位后加“-” 我可以读第9位带“-”的行,但如果第9位不带“-”的话,我就不能写 任何帮助都将不胜感激 不能在VBScript字符串中插入字符,因为这些字符是不可变的;您必须从Left(sOrgStr,8)&“-”和Mid(sOrgStr,9)连接一个新字符串。(数字为+-1,具体取决于您的计数方式。)您可以使用以下代码修复读取的字符串: s="input string" if (mid(s,9,1)<>"-") then 'the 9th cha

我有一个文件有多行

  • 要求每行第8位后加“-”
  • 我可以读第9位带“-”的行,但如果第9位不带“-”的话,我就不能写

任何帮助都将不胜感激

不能在VBScript字符串中插入字符,因为这些字符是不可变的;您必须从
Left(sOrgStr,8)&“-”和Mid(sOrgStr,9)
连接一个新字符串。(数字为+-1,具体取决于您的计数方式。)

您可以使用以下代码修复读取的字符串:

s="input string"
if (mid(s,9,1)<>"-") then 'the 9th character isn't "-"
    s=left(s,8) & "-" & mid(s,9)
end if
s=“输入字符串”
如果(中(s,9,1)“-”,则“第9个字符不是“-”
s=左(s,8)和“-”及中(s,9)
如果结束

我建议您打开文件进行输入,然后将其重新写入另一个文本文件。

您可以使用正则表达式

如果你在一行一行地读,我想你需要

Set objRe = New RegExp
' this will match any line having 9 or more characters,
' where the 9-th character is not "-", and capture the first 8 characters in the group #1
objRe.Pattern = "^(.{8})[^-]"

' Open the file, read lines, in the inner loop, call:
line = objRe.Replace( line, "$1-" ) ' This will replace the RE with the group #1 followed by '-'
这将

  • 打开一个文件
    C:\temp\log.txt
  • 使用单个regexo进行全局更改
  • 将新更新的文本写回原始文件
请更改文件的路径以适合此行
StrFileName=“C:\temp\log.txt”


全球正则表达式替换将比逐行替换更有效line@brettdj:是,但是不能保证整个数据在地址空间中适合两次(特别是在32位平台上):在VBS中,字符串是BSTR,即USC2,即每个字符2个字节。逐行允许处理大型文件。备注:这也会在每行末尾添加短于8个字符的破折号(-)。
Const ForReading = 1    
Const ForWriting = 2
Dim objFSO
Dim objTF
Dim objRexex
Dim StrFileName
Dim strTxt

StrFileName = "C:\temp\log.txt"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTF = objFSO.OpenTextFile(StrFileName, ForReading)
Set objregex = CreateObject("vbscript.regexp")
strTxt = objTF.ReadAll
objTF.Close
With objregex
    .Global = True
    .MultiLine = True
    .Pattern = "^(.{8})[^-](.*)$"
    strTxt = .Replace(strTxt, "$1" & "-" & "$2")
End With

Set objTF = objFSO.OpenTextFile(StrFileName, ForWriting)
objTF.Write strTxt
objTF.Close