【问题标题】:how to replace one line with two lines in txt file如何用两行替换txt文件中的一行
【发布时间】:2018-12-26 13:45:22
【问题描述】:

我想要一些 .cs 模型文件来附加注释。如果脚本找到特定属性,它将放在该属性注释之上。

这是脚本:

$annotation = "[DatabaseGenerated(DatabaseGeneratedOption.Computed)]"
Get-ChildItem -Filter *.cs | % {
(Get-Content $_.FullName) | ForEach-Object { 
    if ($_ -match "StartDateTime") {
        $_ -replace $_ , "`n`t`t$annotation`n$_" 
    }
  } | Set-Content $_.FullName
}

它适用于替换,但最后我得到一个只有两行(注释和自定义属性)的空白文件。我意识到最后一个管道 Set-Content $_.FullName 搞砸了。 如果我删除 Set-Content,我的文件不会发生任何事情(它没有更新)?

【问题讨论】:

  • 您只将匹配的行放入管道中。添加一个 else: else { $_ }

标签: powershell


【解决方案1】:

这应该更适合你:

$filePath = '<YOUR PATH HERE>'
$annotation = "[DatabaseGenerated(DatabaseGeneratedOption.Computed)]"
Get-ChildItem -Path $filePath -Filter *.cs | ForEach-Object {
    $file = $_.FullName
    (Get-Content $file) | ForEach-Object { 
        # test all strings in $file
        if ($_ -match "StartDateTime") {
            # emit the annotation followed by the string itself
            "`r`n`t`t$annotation`r`n" + $_
        }
        else { 
            # just output the line as-is
            $_
        }
    }  | Set-Content -Path $file -Force
}

Foreach-Object 中,我正在捕获$_.FullName 以供以后使用,并且不要将它与您稍后在文件中使用的$_ 混淆。 然后,如果该行与if 匹配,则输出替换的行,但如果不匹配(在else 中),则应输出该行不变。 然后,Set-Content 总是输出每一行,无论是否替换。

由于您实际上并没有替换字符串中的任何内容,而是在其前面加上注释,因此可以将其简化如下:

$annotation = "[DatabaseGenerated(DatabaseGeneratedOption.Computed)]"
Get-ChildItem -Path 'D:\' -Filter *.cs | ForEach-Object {
    $file = $_.FullName
    (Get-Content $file) | ForEach-Object { 
        # test all strings in $file
        if ($_ -match "StartDateTime") {
            # emit the annotation
            "`r`n`t`t$annotation"
        }
        # output the line as-is
        $_
    }  | Set-Content -Path $file -Force
}

【讨论】:

  • 是的,我刚刚意识到我错过了 else 部分。谢谢
猜你喜欢
  • 2022-01-19
  • 1970-01-01
  • 2011-08-31
  • 2022-01-18
  • 2011-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多