Writing content of one file to another using replace mulin powershell

Viewed 34

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
3 Answers

And foreach loop can be deleted

$filecontent = Get-Content "d:\testdir\file1.txt"
(Get-Content -path "d:\testdir\sample.txt").Replace("File1Content","$($filecontent -join [Environment]::NewLine)")| Set-Content d:\testdir\output.txt

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)"

The -Raw parameter is greatly used to boost Get-Content speed. It reads the whole file as a single string skipping the newlines. So the reading is fast. You can try this:

$newcontent = Get-Content "sample.txt" | Foreach { 
  $_ -replace "File1Content", "$(Get-Content file1.txt)"
}
$newcontent | Set-Content output.txt
Related