如何通过搜索旧文件中的特定文本来创建新文件

时间:2015-11-24 09:26:50

标签: vbscript scripting

我的OLDFile看起来像FolderList.txt,内容为:

\\srv10177\temppahir$\Desktop\WORK\6758\Archive\Article\20140825_123400
\\srv10177\temppahir$\Desktop\WORK\6758\Archive\Article\20140827_065126
\\srv10177\temppahir$\Desktop\WORK\6758\Archive\Article\20141006_094447
\\srv10177\temppahir$\Desktop\WORK\6758\Archive\Article\20141006_110546
\\srv10177\temppahir$\Desktop\WORK\6758\Archive\Article\20141008_105947
\\srv10177\temppahir$\Desktop\WORK\6758\Archive\Article\20150917_093710
\\srv10177\temppahir$\Desktop\WORK\6758\Archive\Article\20151005_190254
\\srv10177\temppahir$\Desktop\WORK\6758\Archive\Article\20151005_191124

我想创建一个名为FolderListNew.txt的新文件和内容:

\\srv10177\temppahir$\Desktop\WORK\6758\Archive\Article\20141006_110546
\\srv10177\temppahir$\Desktop\WORK\6758\Archive\Article\20141008_105947
\\srv10177\temppahir$\Desktop\WORK\6758\Archive\Article\20150917_093710
\\srv10177\temppahir$\Desktop\WORK\6758\Archive\Article\20151005_190254

所以基本上我想搜索2个文本:

Text1 = 20141006_110546
Text2 = 20151005_190254

并从第一次出现的Text1中拉出行,直到Text2出现。 假设数据总是这样,并且将按照这些时间戳以升序排序。

我已经尝试了以下脚本,该脚本不起作用且不完整:

Option Explicit
Dim objFSO, msg, Filename, file, filestreamOUT, objFile, strContents, strLine, line, Text1, Text2, OLDFilename, tmpStr, MyPos
Set objFSO = CreateObject("Scripting.FileSystemObject") 
Text1 = "20141006_110546"
Text2 = "20151005_190254"
OLDFilename="C:\Users\IBM_ADMIN\Desktop\VB\Folderlist.txt"
WScript.Echo "String to find is : " & Text1
Wscript.Echo "OLDFilename is " & OLDFilename
Set objFile = objFSO.OpenTextFile(OLDFilename, 1)
Wscript.Echo "Reading file the first time:"
strContents = objFile.ReadAll
Wscript.Echo "Line being read is" & strContents

WScript.Echo "tmpStr.ReadLine is : " & Line
'MyPos = InStr (tmpStr.ReadLine, Text1)
WScript.Echo "MyPos value is : " & MyPos
If MyPos >= 0 Then
  'WScript.Echo "Match NOT Found in File and tmpStr.ReadLine is : " & tmpStr.ReadLine
Else 
  WScript.Echo "string value is : " & strLine
  WScript.Echo "Match Found in File and tmpStr.ReadLine is : " & tmpStr.ReadLine
End If

1 个答案:

答案 0 :(得分:0)

如果您想将一个文件中的特定行放入另一个文件中,最好逐行读取源文件:

Set inFile = objFSO.OpenTextFile(OLDFilename)
Do Untile inFile.AtEndOfStream
  line = inFile.ReadLine
  ...
Loop
inFile.Close

如果该行包含Text1,则开始编写输出文件,并在包含Text2之后停止写入:

Text1 = "20141006_110546"
Text2 = "20151005_190254"

writeOutput = False

Set inFile = objFSO.OpenTextFile("C:\path\to\input.txt")
Set outFile = objFSO.OpenTextFile("C:\path\to\output.txt", 2, True)
Do Until inFile.AtEndOfStream
  line = inFile.ReadLine
  If InStr(line, "20141006_110546") > 0 Then writeOutput = True
  If writeOutput Then outFile.WriteLine line
  If InStr(line, "20151005_190254") > 0 Then Exit Do
Loop
inFile.Close
outFile.Close