1

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.

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

hi, sadly that does not work, for me: Get-Content : A parameter cannot be found that matches parameter name 'raw'.
Which version of PowerShell are you on? The raw parameter was introduced in v3 and the current version is v4. ;-) That said, you can work around this easily enough in v1/v2. I'll update my answer
Thank you very much! thats worked very well! i just had to change the typos. ;-) again, thanks a lot!
@user3245349 Sorry about that. I think I've fixed them all.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.