December 30, 2019 at 1:12 am
I need to once in a while replace a string of about 200 characters in each text file (~ 2 Mb each) with another string of similar length? There are 1000+ files in the directory, and I want to loop through each, replace the string if found, save file, move to next one, and so on in the entire directory. All files have different name but same extension, either .aspx or .txt.
It doesn't have to be necessarily a T-SQL solution but ANY way that will not involve substantial programming or time-consuming efforts.
Likes to play Chess
December 30, 2019 at 1:13 am
it is Windows 10 or Win Server 2016 OS.
Likes to play Chess
December 30, 2019 at 1:21 am
There's probably a better way, but one option is to automate Word.
Open file,
Run Replace
Save
Go to next file. (you can use DIR() to get the next file)
December 30, 2019 at 8:41 am
use powershell for that - easy in just a few lines.
see https://powershell.org/forums/topic/find-and-replace-strings-in-multiple-files/
December 30, 2019 at 9:09 am
I agree that Powershell would be far easier, and could easily be executed by an Agent Task in SQL Server if needed. Should look something like this:
$Directory = "C:\temp\YourDirectory"
$Files = Get-ChildItem -Path $Directory #-Recurse #Uncomment if needed
foreach ($File in $Files)
{
(Get-Content $File) -replace "Find String","Replacement String" | Set-Content $File
}
Thom~
Excuse my typos and sometimes awful grammar. My fingers work faster than my brain does.
Larnu.uk
December 30, 2019 at 4:56 pm
I agree that Powershell would be far easier, and could easily be executed by an Agent Task in SQL Server if needed. Should look something like this:
$Directory = "C:\temp\YourDirectory"
$Files = Get-ChildItem -Path $Directory #-Recurse #Uncomment if needed
foreach ($File in $Files)
{
(Get-Content $File) -replace "Find String","Replacement String" | Set-Content $File
}
I really like Thom's answer. I would just consider adding the following to the $Files variable to filter to specific extensions you're looking for:
$Files = Get-ChildItem -Path $Directory -Include *.aspx, *.txt #-Recurse #Uncomment if needed
December 31, 2019 at 9:28 am
I really like Thom's answer. I would just consider adding the following to the $Files variable to filter to specific extensions you're looking for:
$Files = Get-ChildItem -Path $Directory -Include *.aspx, *.txt #-Recurse #Uncomment if needed
Very good point, and an oversight on my part. I should have more carefully noted the OP was only looking at specific extensions. ????
Thom~
Excuse my typos and sometimes awful grammar. My fingers work faster than my brain does.
Larnu.uk
Viewing 8 posts - 1 through 7 (of 7 total)
You must be logged in to reply to this topic. Login to reply