使用 replace mulin powershell 将一个文件的内容写入另一个文件
Writing content of one file to another using replace mulin powershell
我有两个包含以下内容的文本文件
file1.txt
Abcd
Efgh
HIJK
sample.txt
Some pre content goes here
File1Content
现在我要做的是从 file1.txt 中读取所有内容并使用 sample.txt 并用 file1.txt 的实际内容替换 File1Content 词,但它以单个形式提供输出行。
output.txt 应该是这样的
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
参数用于提高 Get-Content 速度。它将整个文件作为单个字符串读取,跳过换行符。所以阅读速度很快。你可以试试这个:
$newcontent = Get-Content "sample.txt" | Foreach {
$_ -replace "File1Content", "$(Get-Content file1.txt)"
}
$newcontent | Set-Content output.txt
我有两个包含以下内容的文本文件
file1.txt
Abcd
Efgh
HIJK
sample.txt
Some pre content goes here
File1Content
现在我要做的是从 file1.txt 中读取所有内容并使用 sample.txt 并用 file1.txt 的实际内容替换 File1Content 词,但它以单个形式提供输出行。
output.txt 应该是这样的
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
参数用于提高 Get-Content 速度。它将整个文件作为单个字符串读取,跳过换行符。所以阅读速度很快。你可以试试这个:
$newcontent = Get-Content "sample.txt" | Foreach {
$_ -replace "File1Content", "$(Get-Content file1.txt)"
}
$newcontent | Set-Content output.txt