【问题标题】:powershell find and replace text in each file with specific match and extensionpowershell 在每个文件中查找并替换具有特定匹配和扩展名的文本
【发布时间】:2019-06-26 21:46:12
【问题描述】:

我正在尝试做两件事。首先我要在匹配后删除所有文本,然后用新文本替换匹配行。

在下面的示例中,我想找到行 List of animals 并将所有文档 *.txt 中的所有行替换为 中的文本replaceWithThis.txt.

我下面的第一个 foreach 将删除 动物列表 之后的所有内容,我的第二个 foreach 将替换 动物列表 并因此在该行之后添加新内容replaceWithThis.txt

replaceWithThis.txt 包含:

List of animals
Cat 5
Lion 3
Bird 2

*.txt 包含:

List of cities
London 2
New York 3
Beijing 6

List of car brands
Volvo 2
BMW 3
Audi 5

List of animals
Cat 1
Dog 3
Bird 7

代码:

$replaceWithThis = Get-Content c:\temp\replaceWithThis.txt -Raw

$allFiles = Get-ChildItem "c:\temp" -recurse | where {$_.extension -eq ".txt"}
$line = Get-Content c:\temp\*.txt | Select-String cLuxPlayer_SaveData | Select-Object -ExpandProperty Line
foreach ($file in $allFiles)
{
    (Get-Content $file.PSPath) |
    ForEach-object { $_.Substring(15,  $_.lastIndexOf('List of animals')) } |
    Set-Content $file.PSPath
}

foreach ($file in $allFiles)
{
    (Get-Content $file.PSPath) |
    Foreach-Object { $_ -replace $line,$replaceWithThis } |
    Set-Content $file.PSPath
}

所有(*.txt)的最终结果应该是:

List of cities
London 2
New York 3
Beijing 6

List of car brands
Volvo 2
BMW 3
Audi 5

List of animals
Cat 5
Lion 3
Bird 2

【问题讨论】:

    标签: powershell replace foreach


    【解决方案1】:

    使用正则表达式,下面的代码应该可以工作:

    $filesPath       = 'c:\temp'
    $replaceFile     = 'c:\temp\replaceWithThis.txt'
    $regexToFind     = '(?sm)(List of animals(?:(?!List).)*)'
    $replaceWithThis = (Get-Content -Path $replaceFile -Raw).Trim()
    
    Get-ChildItem -Path $filesPath -Filter *.txt | ForEach-Object {
        $content = $_ | Get-Content -Raw
        if ($content -match $regexToFind) {
            Write-Host "Replacing text in file '$($_.FullName)'"
            $_ | Set-Content -Value ($content -replace $matches[1].Trim(), $replaceWithThis) -Force
        }
    }
    

    正则表达式详细信息

    (                      Match the regular expression below and capture its match into backreference number 1
       List of animals     Match the characters “List of animals” literally
       (?:                 Match the regular expression below
          (?!              Assert that it is impossible to match the regex below starting at this position (negative lookahead)
             List          Match the characters “List” literally
          )
          .                Match any single character
       )*                  Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
    )
    

    【讨论】:

    • 非常感谢 Theo,它运行良好! :) 感谢 Regex 的解释,它总是让我头疼,所以我通常会尽量避免它。
    猜你喜欢
    • 2011-02-19
    • 1970-01-01
    • 2011-03-10
    • 1970-01-01
    • 1970-01-01
    • 2011-03-13
    • 2011-08-21
    • 2019-07-21
    相关资源
    最近更新 更多