Link to home
Start Free TrialLog in
Avatar of SCMCEN
SCMCEN

asked on

Replace multiple text values within every file of a selected folder

I have searched and tried all kinds of scripts and have not found what I am looking for. I cannot use a shareware app as it is against the network security rules to install any shareware. I have to use standard scripting tools.

I have a large number of text files that need to have multiple values changed in each file. I have found a script that will make the change but I have to set the file name, string to search, and string to replace each time. I want to be able to create a list of values to search for and their corresponding replacement value. Then set a base folder that the code will search each file within the folder and replace each of the listed values. i.e. Within every file in a designated folder replace every instance of "Thomas" with "Tom", every instance of "Susan" with "Sue" etc. The code I am using now is:

Option Explicit

Dim fso,strFilename,strSearch,strReplace,objFile,oldContent,newContent
 
strFilename="C:\Files\Test1.txt"
strSearch="Thomas"
strReplace="Tom"
 
'Does file exist?
Set fso=CreateObject("Scripting.FileSystemObject")
if fso.FileExists(strFilename)=false then
   wscript.echo "file not found!"
   wscript.Quit
end if
 
'Read file
set objFile=fso.OpenTextFile(strFilename,1)
oldContent=objFile.ReadAll
 
'Write file
newContent=replace(oldContent,strSearch,strReplace,1,-1,0)
set objFile=fso.OpenTextFile(strFilename,2)
objFile.Write newContent
objFile.Close

Open in new window

Avatar of oBdA
oBdA

How about a few lines of Powershell? This will overwrite the processed files (as your script does) but could easily be changed to use new names or a different target directory. The replacement is currently case sensitive.
$BaseFolder = "C:\Files"
$Filter = "*.txt"
$Replace = @{
	"Thomas" = "Tom"
	"Susan" = "Sue"
}
Get-ChildItem -Path $BaseFolder -Filter $Filter | % {
	"Processing $($_.FullName) ..." | Write-Host
	$Content = Get-Content -Path $_.FullName | Out-String
	$Replace.GetEnumerator() | % {$Content = $Content.Replace($_.Name, $_.Value)}
	$Content | Set-Content -Path $_.FullName
}

Open in new window

Avatar of SCMCEN

ASKER

Thanks for the quick response. Unfortunately Powershell cannot be run on my machine due to network security rules.
ASKER CERTIFIED SOLUTION
Avatar of Robert Schutt
Robert Schutt
Flag of Netherlands image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of SCMCEN

ASKER

Perfect and simple answer. Thank You!!