我觉得楼主的要求用vbs实现起来稳妥点,加上了排序显示功能,看起来有点臃肿。
搜索匹配的是:S后面跟几个数字和M03
把vbs放到待处理txt文件一起运行- Option Explicit
- Dim FSO,file,ofile,strText
- Set FSO=CreateObject("scripting.filesystemobject")
- For Each file In FSO.GetFolder(".").Files
- If LCase(FSO.GetExtensionName(file))="txt" Then
- Set ofile=FSO.OpenTextFile(file,1)
- strText=ofile.ReadAll():ofile.Close
- Set ofile=FSO.OpenTextFile(file,2)
- ofile.Write(ShowAndReplace(strText,file.Name))
- ofile.Close
- End If
- Next
- WScript.Echo "处理结束!"
-
- Function ShowAndReplace(str,filename)
- Dim Matches,Match
- Dim i,j,intCount,dicTmp,strTmp,strShow,strSource
- With CreateObject("vbscript.regexp")
- .Global=True
- .IgnoreCase=True
- .Multiline=True
- .pattern="S[1-9]\d*(?=M03)"
- If .Test(str)=True Then
- Set Matches=.Execute(str)
- Set dicTmp=CreateObject("scripting.dictionary")
- For Each Match In Matches
- intCount=intCount+1
- dicTmp.Add intCount,Match
- Next
- '排序
- For i=1 To dicTmp.Count-1
- For j=i+1 To dicTmp.Count
- If dicTmp.Item(i)>dicTmp.Item(j) Then
- strTmp=dicTmp.Item(i)
- dicTmp.Item(i)=dicTmp.Item(j)
- dicTmp.Item(j)=strTmp
- End If
- Next
- Next
- For i=1 To dicTmp.Count
- strShow=strShow&dicTmp.Item(i)&vbCrLf
- Next
- strSource=InputBox(strShow,filename&"的搜索结果,请输入替换值:")
- ShowAndReplace=.Replace(str,strSource)
- Else
- ShowAndReplace=str
- End If
- End With
- End Function
复制代码
|