【问题标题】:Replace a non-unique line of text under a unique line of text in a text file using powershell使用powershell替换文本文件中唯一文本行下的非唯一文本行
【发布时间】:2019-09-24 14:05:07
【问题描述】:

我有以下 txt 文件。

[AppRemover]
Enable=0

[CleanWipe]
Enable=0

[RerunSetup]
Enable=0

如何仅将[CleanWipe] 下的Enable=0 更改为Enable=1

以下是我计划如何将代码与我的文件一起使用。

$Path = C:\temp\file.txt
$File = Get-Content -Path $Path
# Code to update file
$File | Out-File $Path

【问题讨论】:

  • 顺便说一句:考虑使用专用的 INI 文件解析器,例如流行的第三方 INI 文件解析模块 PSIni,其用法在 this answer 中进行了演示。

标签: powershell text replace


【解决方案1】:

如果值为 0,您可以使用-replace 更新该值。

$Path = C:\temp\file.txt
(Get-Content $Path -Raw) -replace "(?<text>\[CleanWipe\]\r?\nEnable=)0",'${text}1' |
    Set-Content $Path

使用解析 INI 文件的模块将是最好的解决方案。我建议尝试PsIni

说明:

-Raw 开关将文件内容作为单个字符串读取。这样可以更轻松地使用换行符。

-replace 执行正则表达式匹配然后替换。以下是正则表达式匹配细分。

  • (?&lt;text&gt;) 是一个命名的捕获组。在该捕获组中匹配的任何内容都可以在替换字符串中作为'${text}' 调用。
  • \[CleanWipe\][CleanWipe] 的文字匹配,同时将 [] 字符转义为 \
  • \r? 是可选的回车
  • \n 是换行符
  • Enable= 是文字匹配
  • 0 是文字匹配

当匹配存在时,替换字符串是捕获组内容和1。从技术上讲,如果您想改用正向后视,则不需要捕获组。积极的后向断言是(?&lt;=)。该解决方案如下所示:

$Path = C:\temp\file.txt
(Get-Content $Path -Raw) -replace "(?<=\[CleanWipe\]\r?\nEnable=)0",'1' |
    Set-Content $Path

-replace 解决方案的问题在于他们编写的解决方案将更新文件,而不管实际对内容进行了更改。您需要添加一个额外的比较来防止这种情况。其他问题可能是任何这些行上的额外空白。您可以通过在您认为可能存在这些可能性的地方添加 \s* 来解决这一问题。


更多步骤的替代方案:

$file = Get-Content $Path
$TargetIndex = $file.IndexOf('[CleanWipe]') + 1
if ($file[$TargetIndex] -match 'Enable=0') {
    $file[$TargetIndex] = 'Enable=1'
    $file | Set-Content $Path
}

此解决方案仅在满足匹配条件时才更新文件。它使用数组方法IndexOf() 来确定@​​987654343@ 的位置。然后假设您要更改的行在下一个索引中。

IndexOf() 不是查找索引的唯一方法。该方法要求您的行与字符串完全匹配。您可以使用Select-String(默认不区分大小写)返回行号。因为它将是一个行号而不是一个索引(索引从 0 开始,而行号从 1 开始),它总是你想要的索引号。

$file = Get-Content $Path
$TargetIndex = ($file | Select-String -Pattern '[CleanWipe]' -SimpleMatch).LineNumber
if ($file[$TargetIndex] -match 'Enable=0') {
    $file[$TargetIndex] = 'Enable=1'
    $file | Set-Content $Path
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-03
    • 1970-01-01
    • 2021-01-12
    • 1970-01-01
    • 2012-03-19
    • 2021-09-17
    相关资源
    最近更新 更多