【发布时间】:2021-11-12 02:32:33
【问题描述】:
我想将内容添加到 Powershell 中文本文件的特定位置。 我尝试使用添加内容,但它在文件末尾添加文本。
【问题讨论】:
标签: powershell
我想将内容添加到 Powershell 中文本文件的特定位置。 我尝试使用添加内容,但它在文件末尾添加文本。
【问题讨论】:
标签: powershell
这是您可以做到这一点的一种方法。基本上只需将整个文件存储在一个变量中,然后遍历所有行以找到 where 您要插入新文本行的位置(在我的情况下,我是根据搜索来确定的标准)。然后将新文件输出写回文件,覆盖它:
$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*"
【讨论】: