user3245349
user3245349

Reputation: 13

Powershell Script to replace a string with contents from a different text file keeping linebreaks

I have to replace a string within a file with contents from a different file BUT I need to keep the linebreaks. The original file has text before and after the insertion spot.

I am trying to do this with the code below:

$v_notes = Get-Content -path $cp_file_temp_rep
$file = Get-Content -path $ip_file_template |
ForEach-Object {
  $line2 = $_
  $line2 -replace "placenoteshere", $v_notes |
} 
Set-Content -Path $op_file_replaced -value $file

Maybe adding the lines from the $v_notes into $file works, but I just don't get how to achive this.

Upvotes: 1

Views: 2958

Answers (1)

Keith Hill
Keith Hill

Reputation: 201672

Get-Content defaults to processing a file line-by-line. If the file isn't huge you may find it easier to read the whole file in as a string e.g.:

$v_notes = Get-Content $cp_file_temp_rep -raw
$file = Get-Content $ip_file_template -raw
$file = $file -replace "placenoteshere",$v_notes
$file | Out-File $ip_file_template -Encoding ascii

Use the appropriate encoding when writing the file contents back out. The default in PowerShell for Out-File is Unicode.

If you are on v1/v2:

$v_notes = [IO.File]::ReadAllText($cp_file_temp_rep)
$file = [IO.File]::ReadAllText($ip_file_template)
$file = $file -replace "placenoteshere",$v_notes
$file | Out-File $ip_file_template -Encoding ascii

Note that .NET method calls that require a path will need the full path.

Upvotes: 3

Related Questions