在Powershell中将内容插入到文本文件的特定位置

4

我希望在Powershell中将内容添加到文本文件的特定位置。我尝试使用Add Content,但它只会将文本添加到文件末尾。

1个回答

7

以下是一种方法,基本上只需要将整个文件存储在一个变量中,然后遍历所有行以找到您想要插入新文本的位置(在我的情况下,我根据搜索条件确定这一点)。然后将新文件输出写回文件,覆盖它:

$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*"

我将此嵌入脚本中。Out-File 创建了“null 字节”,导致 Python 解释器出现错误。改用 Set-Content 取代 Out-File 解决了这个问题。 - Tu.Ma.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接