Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Recursive replace in files (PowerShell)
$find = 'jquery-1\.4\.4'
$replace = 'jquery-1\.5\.1'
$match = '*.cshtml' , '*.vbhtml'
$preview = $true
foreach ($sc in dir -recurse -include $match | where { test-path $_.fullname -pathtype leaf} ) {
select-string -path $sc -pattern $find
if (!$preview) {
(get-content $sc) | foreach-object { $_ -replace $find, $replace } | set-content $sc
}
}
@jongalloway

This comment has been minimized.

@writeameer

This comment has been minimized.

Copy link

commented Dec 29, 2011

$find = 'jquery-1.5.1'
$replace = 'jquery-1.6.1'
$match = ' *.cshtml' , ' *.vbhtml'

Remove "-whatif" to affect changes

gci -r -i $match | % {
(gc $_ ) | % { $_ -replace $find, $replace } | sc $_ -whatif
}

@yzorg

This comment has been minimized.

Copy link

commented Jan 1, 2012

dir -r -i $match | sls $find -list | select -exp Path | %{
echo 'more stuff here, maybe tf edit ...';
(gc $) | # in parens so file won't be in use during Set-Content
%{ $
-replace $find,$replace } |
sc $_ -WhatIf:$preview # to keep variable in control, if that is being passed as param
}

If you need the Select-String you can place it inline (in case you need to check-out the file from archaic SCM, say TFS). Personally I dislike using GCI, I really prefer DIR or LS. I'm really surprised SLS doesn't have a built-in recurse param (grep), until then I'll keep hiding it behind 'DIR -R'.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.