【问题标题】:Insert Content into specific place in Text File in Powershell将内容插入到 Powershell 文本文件中的特定位置
【发布时间】:2021-11-12 02:32:33
【问题描述】:

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

【问题讨论】:

    标签: powershell


    【解决方案1】:

    这是您可以做到这一点的一种方法。基本上只需将整个文件存储在一个变量中,然后遍历所有行以找到 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*"
    

    【讨论】:

    • 我已将此嵌入脚本中。 Out-File 正在创建破坏 Python 解释器的“空字节”。使用 Set-Content 而不是 Out-File 解决了它。
    猜你喜欢
    • 1970-01-01
    • 2013-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-30
    相关资源
    最近更新 更多