RE: Search & Replace by kevshaw
kevshaw
Fri May 12 09:30:02 CDT 2006
Timm,
The following searches all files recursively below a specified path. When a
file is found, it is opened and read to a single string. The replace method
is then called to change sOldEmail to sNewEmail and modified string is
written back to the file.
----------------
'replace string sOldEmail with string sNewEmail in all files found in string
sPath
Option Explicit
Dim sOldEmail, sNewEmail, sPath
sOldEmail = "me@sales.com"
sNewEmail = "xxx@sales.com"
sPath = "C:\TEMP"
Dim oFS 'file system object
Set oFS = WScript.CreateObject("Scripting.FileSystemObject")
ReplaceEmail sPath, oFS
Sub ReplaceEmail(path, fso)
Dim oFC 'file collection object
Dim oFolder 'folder object
Dim eFile 'file element
Dim eFolder 'folder element
Dim oFile 'file object
Dim oTS 'text stream object
Dim sOldFileText 'holds original file text
Dim sNewFileText 'holds file after replacement
Set oFC = fso.GetFolder(path)
For Each eFile In oFC.Files 'do email replacement work here
Set oFile = fso.GetFile(eFile.Path)
Set oTS = oFile.OpenAsTextStream(1) 'for reading
sOldFileText = oTS.ReadAll
sNewFileText = Replace(sOldFileText, sOldEmail, sNewEmail)
Set oTS = oFile.OpenAsTextStream(2) 'for writing
oTS.Write(sNewFileText)
Next
Set oFolder = oFC.SubFolders
'calls itself for each folder
For Each eFolder In oFolder
ReplaceEmail eFolder.Path, fso
Next
End Sub
----------------
Key features are recursion, use of the FileSystem and File objects and the
Replace function for strings. Enjoy.
-Kevin
"Timm Herget" wrote:
> Hello together,
>
> when I copy our ~1000 Intranet Websites from Live Intranet to my Test VMWare
> Intranet I must change the emails in the Website Codes everytime I do the
> "place-change". So for example I must search & replace "me@sales.com" to
> "xxx@sales.com" everytime I copy the files back to the Live Intranet Folder
> and this for all 1000 Files. Have to do this with 2 different Mail
> adresses.... For sure, many Editors allow it to read in whole directories
> and search and replace there but .... Maybe there is a way to write a script
> which does the search & replace thing automatically by just double clicking?
> Does anyone know a solution for my problem? Would be very nice!
>
>
> Thanks in advance.
> Timm Herget
>
>
>