PoshCode Archive  Artifact [0e4e0a3a44]

Artifact 0e4e0a3a447ab53250e1c482d7b344d5b8c98399d476f5f4f46aca620ff6519e:

  • File Replace-InTextFile.ps1 — part of check-in [3caa326506] at 2018-06-10 13:00:18 on branch trunk — A script to do replace strings in text files. Yes, this is just a wrapper around (gc) -replace | sc (user: Joel Bennett size: 1807)

# encoding: ascii
# api: powershell
# title: Replace-InTextFile
# description: A script to do replace strings in text files. Yes, this is just a wrapper around (gc) -replace | sc
# version: 0.1
# type: function
# author: Joel Bennett
# license: CC0
# function: CReplace-String
# x-poshcode-id: 1707
# x-archived: 2016-03-05T20:24:33
# x-published: 2011-03-16T13:29:00
#
#
# Replace-InTextFile.ps1
# Replace Strings in files
param ( 
        [string] $Path = "."
      , [string] $Filter           # Select no files, by default....
      , [string] $pattern = $(Read-Host "Please enter a pattern to match")
      , [string] $replace = $(Read-Host "Please enter a replacement string")
      , [switch] $recurse = $false
      , [switch] $caseSensitive = $false
)

if ($pattern -eq $null -or $pattern -eq "") { Write-Error "Please provide a search pattern!" ; return }
if ($replace -eq $null -or $replace -eq "") { Write-Error "Please provide a replacement string!" ; return }

function CReplace-String( [string]$pattern, [string]$replacement )
{
   process { $_ -creplace $pattern, $replacement }
}
function IReplace-String( [string]$pattern, [string]$replacement )
{
   process { $_ -ireplace $pattern, $replacement }
}

$files = Get-ChildItem -Path $Path -recurse:$recurse -filter:$Filter

foreach($file in $files) {
   Write-Host "Processing $($file.FullName)"
   if( $caseSensitive ) {
      $str = Get-Content $file.FullName | CReplace-String $pattern $replace
      Write-Host $str
      Set-Content $file.FullName $str
   } else {
      $str = Get-Content $file.FullName | IReplace-String $pattern $replace
      Write-Host $str
      Set-Content $file.FullName $str
   }
}

if($files.Length -le 0) { 
   Write-Warning "No matching files found"
}