Skip to content

Instantly share code, notes, and snippets.

@mattia72
Last active March 21, 2025 09:44
Show Gist options
  • Save mattia72/b44133064f005f96a4d1779e5270b5e6 to your computer and use it in GitHub Desktop.
Save mattia72/b44133064f005f96a4d1779e5270b5e6 to your computer and use it in GitHub Desktop.
Replace file content in a range with ripgrep
$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