Показать полную графическую версию : [решено] VBS, поиск во всех файлах заданной папки и запись в файл.
Привет, скорректируйте пожалуйста.
В заданной папке (C:\old) есть 520 файлов. В каждом файле нужно выполнить построчный поиск, если в строке есть заданное слово, то записать строку в файл (output.txt должен содержать информацию из 520 файлов).
В моем случае работает если явно указать имя файла, а мне нужно, чтобы поиском пройтись по всем 520 и записать всю найден. информацию в один файл output.txt.
Option Explicit
Dim fso, tsIn, tsOut, str
Set fso= Createobject("Scripting.FileSystemObject")
Set tsIn = fso.OpenTextFile("C:\old\filelog.2010-10-04", 1, 0) ' открываем файл для чтения, в ASCII
Set tsOut = fso.CreateTextFile("output.txt", True, False) 'создаём файл в ASCII, при наличии файл перезаписывается
Do While Not tsIn.AtEndOfStream
str = tsIn.ReadLine 'читаем построчно исходный файл
If InStr(1, str, "Мой текст", 1) <> 0 Then 'ищем искомое слово в строке
tsOut.WriteLine str 'записываем найденную строку в выходной файл
End If
Loop
tsIn.Close
tsOut.Close
Set fso = Nothing
а мне нужно, чтобы поиском пройтись по всем 520 »
…
Set tsOut = fso.CreateTextFile("output.txt", True, False)
For Each objFile In objFSO.GetFolder("C:\old").Files
Set tsIn = objFile.OpenAsTextStream(…)
…
Next
…
спасибо, а можно привести готовый вариант, попытался объединить имеющийся свой и ваш, не привело к желаемому результату
vlad20, примерно так (не проверялось):
Option Explicit
Dim strSourceFolder
Dim strOutputFile
Dim strText4Find
Dim objFSO
Dim objFile
Dim objTSOutput
Dim objTSInput
Dim strValue
strSourceFolder = "C:\old"
strOutputFile = "output.txt"
strText4Find = "Мой текст"
With WScript.CreateObject("Scripting.FileSystemObject")
If .FolderExists(strSourceFolder) Then
Set objTSOutput = .CreateTextFile(strOutputFile, True)
For Each objFile In .GetFolder(strSourceFolder).Files
With objFile.OpenAsTextStream()
Do Until .AtEndOfStream()
strValue = .ReadLine()
If InStr(strValue, strText4Find, vbTextCompare) <> 0 Then
objTSOutput.WriteLine strValue
End If
Loop
.Close
End With
Next
objTSOutput.Close
Set objTSOutput = Nothing
Else
WScript.Echo "Source folder [" & strSourceFolder & "] not found"
WScript.Quit 1
End If
End With
WScript.Quit 0
В результате выполнения кода (http://forum.oszone.net/post-1959926-4.html) получается Ошибка: Объект не поддерживает это свойство или метод: 'AtEndOfStream'
вышел из ситуации так, "слил" все файлы в один Dim objFSO: Set objFSO = CreateObject("Scripting.FileSystemObject")
JoinTXT "C:\old"
Sub JoinTXT(strFolderPath)
Dim objFolder, objFile, strTempText, strAllText
If objFSO.FolderExists(strFolderPath) Then
Set objFolder = objFSO.GetFolder(strFolderPath)
For Each objFile In objFolder.Files
strExt = LCase(objFSO.GetExtensionName(objFile.Path))
If (strExt = "txt") Or (strExt = "log") Then
strTempText = ReadFile(objFile.Path)
If strTempText <> "" Then
strAllText = strAllText & strTempText & vbCrLf & "===== " & objFile.Name & " =====" & vbCrLf
End If
'objFile.Delete True ' удалить файл
End If
Next
End If
Set objFile = objFSO.CreateTextFile(strFolderPath & "\AllTextFiles.txt")
objFile.Write strAllText
objFile.Close
End Sub
MsgBox "выход"
Set objFSO = Nothing
Wscript.quit
Function ReadFile(strTempFilePath)
On Error Resume Next
Dim objTempFile, strText
Set objTempFile = objFSO.OpenTextFile(strTempFilePath, 1, False)
strText = objTempFile.Readall
objTempFile.Close
ReadFile = strText
End Function
и выполнил построчный поиск
Option Explicit
Dim fso, tsIn, tsOut, str
Set fso= Createobject("Scripting.FileSystemObject")
Set tsIn = fso.OpenTextFile("C:\old\filelog.2010-10-04", 1, 0) ' открываем файл для чтения, в ASCII
Set tsOut = fso.CreateTextFile("output.txt", True, False) 'создаём файл в ASCII, при наличии файл перезаписывается
Do While Not tsIn.AtEndOfStream
str = tsIn.ReadLine 'читаем построчно исходный файл
If InStr(1, str, "Мой текст", 1) <> 0 Then 'ищем искомое слово в строке
tsOut.WriteLine str 'записываем найденную строку в выходной файл
End If
Loop
tsIn.Close
tsOut.Close
Set fso = Nothing
Проверенный ;) вариант.
1. «.AtEndOfStream» — свойство. Исправьте:
Do Until .AtEndOfStream()
на:
Do Until .AtEndOfStream
2. Забыл, что:
start
Optional. Numeric expression that sets the starting position for each search. If omitted, search begins at the first character position. If start contains Null, an error occurs. The start argument is required if compare is specified.
Исправьте:
If InStr(strValue, strText4Find, vbTextCompare) <> 0 Then
на:
If InStr(1, strValue, strText4Find, vbTextCompare) <> 0 Then
© OSzone.net 2001-2012
vBulletin v3.6.4, Copyright ©2000-2025, Jelsoft Enterprises Ltd.