使用replace mulin powershell将一个文件的内容写入另一个文件

使用replace mulin powershell将一个文件的内容写入另一个文件,powershell,powershell-4.0,Powershell,Powershell 4.0,我有两个文本文件,其中包含以下内容 file1.txt Abcd Efgh HIJK sample.txt Some pre content goes here File1Content 现在我要做的是从file1.txt读取所有内容,使用sample.txt并用file1.txt的实际内容替换File1Content word,但它只提供单行输出 output.txt应该如下所示 Some pre content goes here Abcd Efgh HIJK Some pre c

我有两个文本文件,其中包含以下内容

file1.txt

Abcd
Efgh
HIJK
sample.txt

Some pre content goes here


File1Content
现在我要做的是从file1.txt读取所有内容,使用sample.txt并用file1.txt的实际内容替换File1Content word,但它只提供单行输出

output.txt应该如下所示

Some pre content goes here
Abcd
Efgh
HIJK
Some pre content goes here
Abcd  Efgh    HIJK
但现在看起来是这样的

Some pre content goes here
Abcd
Efgh
HIJK
Some pre content goes here
Abcd  Efgh    HIJK
我正在使用下面的代码,我尝试添加r和n,但它不起作用。有人能帮忙吗

$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

您必须将换行符添加到
$filecontent
中的每个条目中。您可以使用
-join
操作符执行此操作:

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

并且可以删除foreach循环

$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

-Raw
参数可大大提高获取内容的速度。它将整个文件作为一个字符串读取,跳过换行符。所以阅读速度很快。您可以尝试以下方法:

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

-Raw
将整个文件读取为单个字符串,而不是字符串数组(基本上是行)。这就是为什么会发生这种情况的原因——马丁斯答案中的新行建议可能会解决这个问题。