mistux Site Admin
Joined: 25 Jun 2004 Posts: 1042 Location: South Bend, Indiana USA
|
Posted: Mon Sep 18, 2006 8:32 am Post subject: Search For Text Files Using String Expressions |
|
|
Code: |
Option Explicit
'*****************************************************************************************
'Script: searchreplace.vbs
'Version: 1.0
'Created: January 22, 2003
'Author: Mick Montgomery
'
'Credits:
'Many thanks to those who have posted to cwashington.netreach.net,
'some parts of this script were cut and paste from posted scripts.
'
'Purpose/Usage:
'This script allows users to drag and drop multiple files on to it
'for search and replace. You can also call it from the command line
'Example: cscript.exe searchandreplace c:\folder\filename.ext c:\folder2\filename2.ext
'My favorite use is to create a shortcut to the script under your "sendto" menu. You can
'select multiple files, right click and send them to the script.
'
'Caveats:
'Use of ReadAll makes this memory intensive on large files
'*****************************************************************************************
Const ForReading = 1, ForWriting = 2
DIM strFile ' as file or files to search
DIM strFindString ' as string to match
DIM strReplaceString ' as string to replace with
DIM objWshShell ' as Windows Scripting object
DIM objArgs ' as Command line arguments
DIM aFilesToSearch ' as array of files to search
DIM strLogFile ' as file to log results to
DIM objFSO ' as File System object
DIM objTargetFile ' as Target file object
DIM objTextStream ' as text stream to write
DIM strNotFound ' as files not found
DIM strFilesZero ' as files with 0 KB data
DIM strFilesFound ' as files that replace routine was executed successfully
DIM strLog ' as text to write to log file
DIM strMessage ' as message for results type popup
DIM iFormat ' as results selection
DIM Results ' as container for results display
DIM strFileContents ' as contents of file being searched
DIM iWarning ' as warining selection
DIM bBadFiles ' as nontext file flag
DIM objRegExp ' as regular expression object
DIM aIllegalFiles ' as list of file extensions that are not compatible with this script
DIM item, strFileList, iListLength, iReturnErrorCode
' Log file path and name
strLogFile = "C:\My Documents\searchANDreplace.log"
' Incompatible files
ReDim aIllegalFiles(9) 'make sure this number matches the number of items in the array!
aIllegalFiles(0) = "\.xls" 'Excel file
aIllegalFiles(1) = "\.xlt" 'Excel template
aIllegalFiles(2) = "\.doc" 'Word document
aIllegalFiles(3) = "\.ppt" 'Power Point file
aIllegalFiles(4) = "\.pdf" 'Acrobat file
aIllegalFiles(5) = "\.exe" 'Executable file
aIllegalFiles(6) = "\.pst" 'Outlook personal file
aIllegalFiles(7) = "\.ost" 'Outlook offline file
aIllegalFiles(8) = "\.mdb" 'Access Database
aIllegalFiles(9) = "\.pot" 'Power Point template
'***** Main Execution Code *****
' File to search
strFile=getArguments()
bBadFiles=verifyFileTypes(strFile)
If bBadFiles Then ' stop the script, nontext files selected
warning()
WScript.Quit(0)
End If
'String to search for and replace
strFindString=inputbox("Please input the text to search for", "Search For")
'String to replace with if match found
strReplaceString=inputbox("Please input the replacement text", "Replace With")
' If arguments are good enumerate files for search and replace
If Not strFile="error" Then
aFilesToSearch = split(strFile,"^")
For Each item in aFilesToSearch
iReturnErrorCode=FileSearchReplace(item,strFindString,strReplaceString)
If iReturnErrorCode=53 then strNotFound = strNotFound & item & " not found" & vbCrLf
If iReturnErrorCode=75 then strFilesZero = strFilesZero & item & " 0 KB in size" & vbCrLf
If iReturnErrorCode=0 then strFilesFound = strFilesFound & item & vbCrLf
Next
End If
' Create log entries
strLog = "Search And Replace Log, replace " & strFindString & " with " & strReplaceString & vbCrLf & vbCrLf &_
"SUCCESS:" & vbCrLf & strFilesFound & vbCrLf & "ERRORS:" & vbCrLf & strNotFound & strFilesZero
' Request format for viewing log
formatType()
' Display results
displayResults()
WScript.Quit(0)
'======================================
'***** Functions and Subroutines *****
'======================================
function FileSearchReplace(strFilename,findThis,replaceThis)
Set objFSO = CreateObject("Scripting.FileSystemObject")
If not objFSO.FileExists(strFilename) then 'error trap for file doesn't exist
FileSearchReplace=53
Exit Function
End If
Set objTargetFile = objFSO.GetFile(strFilename)
If objTargetFile.size=0 then ' error. file is 0 bytes
FileSearchReplace=75
Exit Function
End If
Set objTargetFile = objFSO.OpenTextFile(strFilename, ForReading)
strFileContents= objTargetFile.ReadAll
Set objTargetFile = objFSO.OpenTextFile(strFilename, ForWriting, True)
objTargetFile.Write Replace(strFileContents, findThis, replaceThis,1,-1,1)
FileSearchReplace=0 'return ok error code
Set objTargetFile = Nothing
Set objFSO = Nothing
End function
'======================================
'***** Check for Command Line Arguments *****
function getArguments()
Set objWshShell = WScript.CreateObject("WScript.Shell")
Set objArgs = WScript.Arguments
if objArgs.length < 1 then
helpMsg()
getArguments = "error"
elseif objArgs(0)="/?" then
helpMsg()
getArguments = "error"
else
For Each item in objArgs
strFileList = strFileList & item & "^"
Next
iListLength = len(strFileList)-1 'removes last ~ from string
strFileList = left(strFileList,iListLength)
getArguments = strFileList
end if
Set objArgs = Nothing
Set objWshShell = Nothing
end function
'======================================
function verifyFileTypes(RawFileList)
DIM VFTResults
VFTResults = True
Set objRegExp = New RegExp
objRegExp.IgnoreCase = True
For Each item in aIllegalFiles
objRegExp.Pattern = item
If objRegExp.Test(RawFileList) AND (item <> "") Then
VFTResults = True
Exit For
Else
VFTResults = False
End If
Next
Set objRegExp = Nothing
verifyFileTypes = VFTResults
end function
'======================================
sub helpMsg()
WScript.Echo "Script Usage:" & chr(13) & chr(13) &_
"searchreplace.vbs fullfilepathandname" & chr(13) & chr(13) &_
"Example:" & chr(13) & chr(13) &_
"searchreplace.vbs F:\inetpub\wwwroot\myfile.htm" & chr(13) & chr(13) &_
"You can also drag and drop or place a shortcut in the sendto menu to this script." & chr(13)&_
"With the sendto option you can highlight multiple files to search and replace text."
WScript.Quit(0)
end sub
'======================================
sub logFile()
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextStream = objFSO.CreateTextFile(strLogFile)
objTextStream.WriteLine(strLog)
objTextStream.Close
Set objTextStream = Nothing
Set objFSO = Nothing
end sub
'======================================
sub formatType()
Set objWshShell = WScript.CreateObject("WScript.Shell")
strMessage = "Would you like the results in a printable format?"
iFormat = objWshShell.Popup(strMessage, 0, "Results Format:", 36)
strMessage = ""
Set objWshShell = Nothing
end sub
'======================================
sub displayResults()
Set objWshShell = WScript.CreateObject("WScript.Shell")
If iFormat = 7 then
Results = objWshShell.Popup(strLog, 0, "Results:", 0)
Else
logFile()
Results = objWshShell.Run("%windir%\notepad.exe " & strLogFile, 5, True)
End If
Set objWshShell = Nothing
end sub
'======================================
sub warning()
Set objWshShell = WScript.CreateObject("WScript.Shell")
strMessage = "Executing this script against non-text file documents such as .xls, .doc and .pdf" & vbCrLf &_
"files will corrupt the document rendering it unreadable! Please unselect any files" & vbCrLf &_
"with the following extensions:" & vbCrLf & vbCrLf
For Each item in aIllegalFiles
strMessage = strMessage & item & vbCrLf
Next
iWarning = objWshShell.Popup(strMessage, 0, "SCRIPT EXECUTION TERMINATED!")
strMessage = ""
Set objWshShell = Nothing
end sub
|
|
|