Find and replace TEXT with FILENAME

marcoswebot

New Member
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!
 


Neemobeer

Windows Forum Team
Staff member
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
}
 


marcoswebot

New Member
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"
 


Neemobeer

Windows Forum Team
Staff member
Code changed to reflect that
 


Neemobeer

Windows Forum Team
Staff member
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.
 


marcoswebot

New Member
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
 


This website is not affiliated, owned, or endorsed by Microsoft Corporation. It is a member of the Microsoft Partner Program.
Top