I am trying to replace only the first occurrence of a string found within a bunch of text files. I have spent hours on this and can't seem to fix it.
I couldn't get this to work. PowerShell Script to Find and Replace for all Files with a Specific Extension
$text_file_ext = 'txt'
Get-ChildItem $base_dir -Recurse -Include "*.$text_file_ext" |
ForEach-Object { (Get-Content $_.FullName) |
foreach -Begin { $found = $false; $search = 'APPLE' } -Process {
if (! $found -and ($_ -match $search))
{
$_ = $_ -replace $search, ' COFFEE'
$found = $true
}
#$_
Set-Content $_.FullName}
}
I also referenced this: http://www.adamtheautomator.com/use-powershell-to-do-a-findreplace-on-a-set-of-text-files/
Sample Text
Lorem ipsum APPLE dolor sit amet, consectetur adipiscing elit. Donec a pharetra nisl, vitae APPLE vehicula turpis. Aenean eleifend bibendum quam, nec dapibus felis viverra ut. Mauris nec nibh scelerisque, aliquet ligula in, viverra justo. Interdum et malesuada fames ac APPLE ante ipsum primis in faucibus.
Any advice is appreciated.
Final Version Working
$search ="APPLE"
$text_file_ext = 'txt'
Get-ChildItem $base_dir -Recurse -Include "*.$text_file_ext" |
ForEach-Object { (Get-Content $_.FullName -Raw) -replace" (.+?)$search(.+)",'$1COFFEE$2'|
Set-content $_.Fullname
}