Powershell在每个文件中查找并替换具有特定匹配和扩展名的文本

时间:2019-02-02 15:12:10

标签: powershell replace foreach

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

在下面的示例中,我想找到动物列表行,并将所有文档 *。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

1 个答案:

答案 0 :(得分:1)

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

<input type="file" name="file" id="file" multiple required>

正则表达式详细信息

$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
    }
}