Thread: Find/Replace
View Single Post
Old 03-28-2007   #6 (permalink)
aaronlerch@gmail.com


 
 

Re: Find/Replace

On Mar 22, 11:52 pm, "Keith Hill" <r_keith_h...@mailhot.nospamIdotcom>
wrote:
> <eric.eickh...@sbcglobal.net> wrote in messagenews: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


Thanks Keith!

I think this function takes what you wrote and expresses it in an easy
to reuse way (if not a little harder to read):

function Replace-String($find, $replace, $includes)
{
get-childitem $includes | select-string $find -list |% { (get-
content $_.Path) |% { $_ -replace $find, $replace } | set-content
$_.Path }
}

http://www.aaronlerch.com/blog/2007/...-function.html

My System SpecsSystem Spec