Search and replace

Ask your PowerShell-related questions, including questions on cmdlet development!
Forum rules
Do not post any licensing information in this forum.

Any code longer than three lines should be added as code using the 'Select Code' dropdown menu or attached as a file.
Locked
User avatar
fr3288
Posts: 23
Joined: Sun Jan 28, 2007 1:37 am

Search and replace

Post by fr3288 »

Hello:

I'm trying to do a search and replace text in all files in a folder and its sub folders. I don't get erros but it does not replace the text. Here is what I have:

$files = Get-ChildItem "c:test" -recurse foreach ($file in $files)
{$content = Get-Content $file $content -replace ("testing","new text") | Set-Content $file }

Any help will be appreciated. Thanks in advance.

riosf

fr32882008-06-17 13:49:14

User avatar
fr3288
Posts: 23
Joined: Sun Jan 28, 2007 1:37 am

Search and replace

Post by fr3288 »



` worked only if the slash was alone. I tried different ways playing around with it but putting the UNC all together with the escape key ` would not work. Using the ' and double slashes did the trick. It was only needed for the search part. For the replacement text the double slashes were not needed. Here is how my script was finally used:

$files = Get-ChildItem c:test -recurse foreach ($file in $files){$content = Get-Content $file.fullname $content -replace (('myservermysharemyfiles'),('newservernewsharenewfiles')) | Set-Content $file.fullname}

Thanks again for your help.

jvierra
Posts: 14621
Joined: Tue May 22, 2007 9:57 am
Answers: 3
Has voted: 1 time
Been upvoted: 3 times
Contact:

Search and replace

Post by jvierra »

I don't understand what you are trying to do.

"Replace" just takes strings.

The single quote defines a string with no replacement. The doub;e-quote defines a string with substitution capable.

Yo have extra braces which can force a change in the order of processing. Somewhere in all of this you have overcome your initial problem but how you have done it is not clear.

jvierra
Posts: 14621
Joined: Tue May 22, 2007 9:57 am
Answers: 3
Has voted: 1 time
Been upvoted: 3 times
Contact:

Search and replace

Post by jvierra »

Some things are permanently assigned to the classification of 'mysterious sightings'. Loch Ness come to mind.

Doesn't it drive you nuts sometimes?

jvierra
Posts: 14621
Joined: Tue May 22, 2007 9:57 am
Answers: 3
Has voted: 1 time
Been upvoted: 3 times
Contact:

Search and replace

Post by jvierra »

Joel - right. I forgot that in PoSH the first arg of the replace is RegEx enabled.

Thanks.

User avatar
joel.delatorre
Posts: 83
Joined: Tue Dec 16, 2008 5:51 am

Search and replace

Post by joel.delatorre »

np, I remember reading that in MOW's blog way back when.

Locked