Last active
March 21, 2025 09:44
-
-
Save mattia72/b44133064f005f96a4d1779e5270b5e6 to your computer and use it in GitHub Desktop.
Replace file content in a range with ripgrep
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$r = @{ | |
Pattern = '(some)?text'; | |
Replacement = 'some other text'; | |
StartLine = 3553; | |
EndLine = 6236; | |
File = '\file.txt' | |
RgArgs = @( | |
'--case-sensitive', | |
'--encoding=windows-1252', | |
'--crlf', | |
'--vimgrep' | |
) | |
} | |
function Get-ReplacedContent { | |
[CmdletBinding()] | |
param ( | |
[string]$File, | |
[string]$Pattern, | |
[string]$Replacement, | |
[int]$StartLine = 0, | |
[int]$EndLine = 0, | |
[Parameter(ValueFromRemainingArguments = $true)] | |
[string[]]$RgArgs | |
) | |
if ({ $($RgArgs -join ' ' ) -notcontains '--vimgrep' }) { | |
$RgArgs += '--vimgrep' | |
} | |
$fileContent = Get-Content $File -Encoding windows-1252 | |
if ($EndLine -eq 0) { $EndLine = $fileContent.Count } | |
&'C:\Program Files\Microsoft VS Code\resources\app\node_modules\@vscode\ripgrep\bin\rg.exe' ` | |
$RgArgs ` | |
--replace="$($Replacement)" ` | |
-- $Pattern ` | |
$File | Select-String -Pattern '^(.*):(\d+):(\d+):(.*)$' | ForEach-Object { | |
$lineNum = $_.Matches.Groups[2].Value | |
if ($lineNum -in ($StartLine..$EndLine)) { | |
@{ | |
LineNum = $lineNum; | |
LineText = "$($_.Matches.Groups[4].Value)" | |
} | |
} | |
} | ForEach-Object { | |
$LineNum = $_.lineNum | |
$fileContent[$LineNum - 1] = "$($_.LineText)" | |
} | |
$fileContent | |
} | |
$newContent = Get-ReplacedContent @r | |
& code --reuse-window --diff "$($r.File)" "$($r.File).new.pas" | |
$answer = Read-Host "Change the original file? [y/n]" | |
if ($answer -match 'y|Y') { | |
$newContent | Set-Content "$($r.File)" -Encoding windows-1252 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment