Windows 10 Find and replace TEXT with FILENAME

marcoswebot

New Member
Joined
Apr 8, 2019
Hello. I have several hundred text files in a folder. I would like to replace the text "Hello" present in every files with the actual "filename".
How to do that? Can I use a Script or PowerShell?

Thank you!
 
With PowerShell

Code:
$SearchDirectory = "C:\path\to\directory"

$Files = Get-ChildItem -Path $SearchDirectory -File

foreach($File in $Files)
{
    $FileData = Get-Content $File.FullName
    $ReplaceString = "Hello"
    $ReplaceData = "Hello+$($File.Name)"

    $NewFileData = $FileData.Replace($ReplaceString,$ReplaceData)
   
    Out-File -FilePath $File.FullName -InputObject $NewFileData -Force
}
 
With PowerShell

Code:
$SearchDirectory = "C:\path\to\directory"

$Files = Get-ChildItem -Path $SearchDirectory -File

foreach($File in $Files)
{
    $FileData = Get-Content $File.FullName
    $ReplaceString = "Hello"
    $ReplaceData = $File.Name

    $NewFileData = $FileData.Replace($ReplaceString,$ReplaceData)
   
    Out-File -FilePath $File.FullName -InputObject $NewFileData -Force
}

Thanks Neemobeer, but this did not work for me.
I did not explain very good. I try again:

What I need to do is to change the TEXT "Hello" with the TEXT "Hello+filename"
 
You need to change the path mentioned in the first line
$SearchDirectory = "C:\path\to\directory"

Otherwise post the error "this is not working" doesn't tell me much.
 
Neemobeer, thanks again for your help.
It works but somehow when I open the file with my program i get this: ÿþ% instead of the full text.
If I open the program with text editor it works but with my special text editor no :-/ Do you know which could be the reason?

Thanks a lot :-D
 
Back
Top Bottom