Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Pattern replacer
<#
.DESCRIPTION
This script is for replacing something by pattern in all text files
in specific directory and its subdirectories recursively.
.PARAMETER word
Pattern what we want to replace.
.PARAMETER replace
Replacement.
.PARAMETER place
Directory where lies files and subdirectories.
.EXAMPLE
.\replace.ps1 -place D:\awesome_stories -word "#define true 1" -replace "#define true 0"
.NOTES
Author: Alex Newlifer - alex.newlifer@gmail.com
#>
param(
[string]$place = $PSScriptRoot,
[string]$word = "",
[string]$replace = ""
)
$regexPattern = $word
if($caseSensitive -eq $false) { $regexPattern = "(?i)$regexPattern" }
$regex = New-Object System.Text.RegularExpressions.Regex $regexPattern
# Function for highlighting pattern in the line.
function Write-HostAndHighlightPattern([string]$inputText)
{
$index = 0
while($index -lt $inputText.Length)
{
$match = $regex.Match($inputText, $index)
if($match.Success -and $match.Length -gt 0)
{
Write-Host $inputText.SubString($index, $match.Index - $index) -nonewline
Write-Host $match.Value.ToString() -ForegroundColor Red -nonewline
$index = $match.Index + $match.Length
}
else
{
Write-Host $inputText.SubString($index) -nonewline
$index = $inputText.Length
}
}
}
$time1 = Get-Date -format HH:mm:ss
$list = Get-ChildItem $place -recurse -Exclude "*.dll", "*.exe", "*.lib", "*.obj", "*.manifest", "*.log", "*.tlog", "*.sdf" | %{Write-Host Examining file: $_.fullname; $_} | ? { $_.psiscontainer -eq $false } | ? { gc $_.pspath | select-string -pattern $word } | % { $_.FullName }
$time2 = Get-Date -format HH:mm:ss
Write-Host "Count of matched files: " $list.Length
$TimeDiff = New-TimeSpan $Time1 $Time2
if ($TimeDiff.Seconds -lt 0) {
$Hrs = ($TimeDiff.Hours) + 23
$Mins = ($TimeDiff.Minutes) + 59
$Secs = ($TimeDiff.Seconds) + 59 }
else {
$Hrs = $TimeDiff.Hours
$Mins = $TimeDiff.Minutes
$Secs = $TimeDiff.Seconds }
$Difference = '{0:00}:{1:00}:{2:00}' -f $Hrs,$Mins,$Secs
$Difference
foreach( $file in $list )
{
$text = get-content $file
$line = $text | select-string -pattern $word -simplematch
Write-Host "Do you really want to replace here? (Y/N)"
Write-HostAndHighlightPattern $line
$yes = Read-Host "`n"
switch( $yes ) {
"Y" {
$newText = $text -replace $word, $replace
$newText > $file
}
"N" {
continue
}
default {
Write-Host "Unknown command " $yes
}
}
}
Write-Host "Work is done!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment