Search code examples
powershellpowershell-4.0

Writing content of one file to another using replace mulin powershell


I have two text file which contains following

file1.txt

Abcd
Efgh
HIJK

sample.txt

Some pre content goes here


File1Content

Now what i am trying to do is read all content from file1.txt and use sample.txt and replace File1Content word with actual content of the file1.txt but it is providing output in single line.

output.txt should look like this

Some pre content goes here
Abcd
Efgh
HIJK

But it is currently looking like this

Some pre content goes here
Abcd  Efgh    HIJK

I am using following code which works , i tried adding r and n but it doesnt work. Could someone please help

$filecontent = Get-Content "C:\location\file1.txt"
(Get-Content -path C:\Location\sample.txt -Raw)   ForEach-Object { $_ -replace "File1Content", "$filecontent`r`n" } | Set-Content C:\Export\output.txt

Solution

  • You have to add the NewLine to each entry in $filecontent. You could do this using the -join operator:

    $_ -replace "File1Content", "$($filecontent -join [Environment]::NewLine)"