Skip to content

Instantly share code, notes, and snippets.

@jongalloway
Created December 29, 2011 07:56
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save jongalloway/1532778 to your computer and use it in GitHub Desktop.
Save jongalloway/1532778 to your computer and use it in GitHub Desktop.
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
}
}
@writeameer
Copy link

$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
Copy link

yzorg 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