|
Re: Find/Replace <eric.eickhoff@sbcglobal.net> wrote in message news:1174589436.498853.183440@n76g2000hsh.googlegroups.com...
> Hello,
>
> I am just learning PowerShell and need a little guidance.
>
> What I am trying to do is to search a directory recursively for files
> that contain a text string and modify the file(s) by replacing that
> string with other text.
>
> To do the search, I can use:
>
> dir -r c:\temp\* | Select-string "xyz"
>
> but from there, I am not sure how to go about doing the replace in
> each file found.
>
> Can anyone point me in the right direction to accomplish this?
There isn't a native PowerShell cmdlet that replaces strings in files in place. However there is a -replace operator that provides the basic replace functionality. You will need to do this in several steps:
$pattern = 'some search pattern - could be regex'
$replacement = 'some replacement potentially using capture groups like so $1 $2 or ${namedGroup}'
foreach ($file in (gci c:\temp\* -rec)) {
$text = get-content $file
if ($text -match $pattern) {
$text -replace $pattern, $replacement > $file
}
}
--
Keith |