我希望在Powershell中将内容添加到文本文件的特定位置。我尝试使用Add Content,但它只会将文本添加到文件末尾。
我希望在Powershell中将内容添加到文本文件的特定位置。我尝试使用Add Content,但它只会将文本添加到文件末尾。
以下是一种方法,基本上只需要将整个文件存储在一个变量中,然后遍历所有行以找到您想要插入新文本的位置(在我的情况下,我根据搜索条件确定这一点)。然后将新文件输出写回文件,覆盖它:
$FileContent =
Get-ChildItem "C:\temp\some_file.txt" |
Get-Content
$FileContent
<#
this is the first line
this is the second line
this is the third line
this is the fourth line
#>
$NewFileContent = @()
for ($i = 0; $i -lt $FileContent.Length; $i++) {
if ($FileContent[$i] -like "*second*") {
# insert your line before this line
$NewFileContent += "This is my newly inserted line..."
}
$NewFileContent += $FileContent[$i]
}
$NewFileContent |
Out-File "C:\temp\some_file.txt"
Get-ChildItem "C:\temp\some_file.txt" |
Get-Content
<#
this is the first line
This is my newly inserted line...
this is the second line
this is the third line
this is the fourth line
#>
$FileContent[$i] -like "*second*"