
Selecting Text from one file and copying to a different file
Quote:
>I am new to scripting and have the following issue. I have a number of text
>files all in the same directory. I want to search each of the files in this
>folder looking for a particular string eg "teststring" and copy the contents
>from where this string occurs to the end of the file. The string only
>appears once in each file. Then copy the contents to a new file. This has to
>happen for each file in the directory and each copy is appended to a new
>file.
>Thanks in advance
>Kenneth
Ok - I threw together two functions, ScanFolder() and ScanText(). Call
ScanFolder with the path of the folder you wish to look at each file
in, the path where you want the outputted text files to be saved (this
path must exist prior to calling the function), and the search text.
ScanFolder will call ScanText. It will output the files that contain
the searchstring into the directory you specify with a XXX before the
file name.
Anyway, if you copy the text below into a file with a .VBS extension
and run it, you will see the results. I used InputBoxes at the last
line to test the function(s), but you will probably call it with
constants when you are finished debugging this. I haven't tested this
beyond a simple run in my "My Documents" directory so its your job to
debug it and modify it to your needs.
Note that this is using a vbTextCompare search - which is needed if
you need results regardless of the case
("SearchString"=="searchstring"). However, you can speed the search up
if you specify a vbBinaryCompare (=0) instead of a vbTextCompare (=1).
Quote:
>>>>>>>>>>>>>>Code Follows<<<<<<<<<<<<<<<<<<<<<<<<<<<
Function ScanText(FSO, strFilePath, strSearch, strOut)
Dim boolRet
Dim strFileText
Dim ts As TextStream
Dim intPos
Const ForReading = 1
Const TristateFalse = 0
Const vbTextCompare = 1
boolRet = False
If FSO.FileExists(strFilePath) Then
Set ts = FSO.OpenTextFile(strFilePath, _
ForReading, False, TristateFalse)
If Not ts.AtEndOfStream Then
strFileText = ts.ReadAll
intPos = InStr(1, strFileText, strSearch, vbTextCompare)
If intPos > 0 Then
boolRet = True
strOut = Mid(strFileText, intPos)
End If
End If
ts.Close
Set ts = Nothing
End If
ScanText = boolRet
End Function
Sub ScanFolder(strFolderPath, strFindPath, strSearch)
Dim FSO
Dim folA
Dim filA
Dim tsOut
Dim strText
Set FSO = Wscript.CreateObject("scripting.FileSystemObject")
If FSO.FolderExists(strFolderPath) Then
Set folA = FSO.GetFolder(strFolderPath)
For Each filA In folA.Files
If ScanText(FSO, filA.Path, strSearch, strText) Then
Set tsOut = FSO.CreateTextFile( _
FSO.BuildPath(strFindPath, "XXX" & filA.Name), _
True, False)
tsOut.Write strText
tsOut.Close
End If
Next
End If
Set folA = Nothing
Set filA = Nothing
Set tsOut = Nothing
Set FSO = Nothing
End Sub
ScanFolder InputBox("Search Folder"), _
InputBox("Output Directory"), _
InputBox("Search Text")