Friday, April 22, 2011

Search and replace text in multiple files using powershell

I was trying to find and replace a text in multiple files using the powershell script. I got couple of references online and arrived at the below script. I agree that this can be further improvised but could be used as a starting point or quick and dirty solution


$match = "text1 test"
$replacement = ""
$match1 = "text2
test"
$replacement1 = ""
$match2 = "text3 test"
$replacement2 = ""
$match3 = "text4 test"
$replacement3 = ""
$files = Get-childItem
–filter *.txt -path "C:\foo" -recurse


foreach($file in $files)
{
((Get-Content $file.fullname) -creplace
$match,$replacement)
set-content $file.fullname

((Get-Content $file.fullname) -creplace
$match1,$replacement1)
set-content $file.fullname
((Get-Content
$file.fullname)
-creplace $match2,$replacement2) set-content
$file.fullname
((Get-Content $file.fullname) -creplace
$match3,$replacement3) set-content $file.fullname
}


References

powershellcommunity

No comments:

Post a Comment