【问题标题】:Powershell: Multiple replace and deletePowershell:多次替换和删除
【发布时间】:2015-03-15 06:15:27
【问题描述】:

我需要有关此脚本的帮助。我已经慢慢走到这一步了,但现在需要帮助。

我需要一个脚本,它将文本从节的末尾移动到文件中的某个点,然后删除移动的文本。要移动的文本有标记,位置也有。我需要能够在移动后删除文本。还需要对同一目录下的多个txt文件做。

例如:

Sample Input .txt

A;1;1;####; (#### is the location (1) marker)
B
B
B
====-1234 (==== is the find (1) marker)
A;1;1;####; (#### is the location (2) marker)
B
B
B
====-5678 (==== is the find (2) marker)

After processing

A;1;1;1234;
B
B
B
A;1;1;5678;
B
B
B

文本文件可以有多个这样的分组。需要从上到下对每个分组执行此操作。这是我目前所拥有的,它只是移动文本而不是删除。

$file = "C:\Users\NX07934\Documents\Projects\23045\Docs\SampleData\*.txt"
$old = "\####" 

$find = Get-ChildItem $file -recurse| Select-String -pattern "====-*"

$split = $find.ToString().Split("-")
$new = $split[1]


get-childitem "C:\Dir" -recurse -include *.txt | 
select -expand fullname |
    foreach 
    { 
        (Get-Content $_) -replace $old,$new |
        Set-Content $_            
    }

感谢您的所有帮助!

【问题讨论】:

    标签: powershell replace foreach


    【解决方案1】:

    有什么帮助吗?

    $text = 
    @'
    A;1;1;####;
    B
    B
    B
    ====-1234
    A;1;1;####;
    B
    B
    B
    ====-5678
    '@
    
    $regex = 
    @'
    (?ms)(.+?####;
    .+?)
    ====-(\d+)
    '@
    
    ([regex]::matches($text,$regex) |
    foreach {
    $_.groups[1].value -replace '####',($_.groups[2].value)
    }) -join ''
    
    A;1;1;1234;
    B
    B
    B
    A;1;1;5678;
    B
    B
    B
    

    编辑:- 将其应用于文件集合:

    $regex = 
    @'
    (?ms)(.+?####;
    .+?)
    ====-(\d+)
    '@
    
    Get-Childitem -Path C:\somedir -Filter *.txt |
    foreach {
    
        $Text = Get-Content $_ -Raw
    
        ([regex]::matches($text,$regex) |
        foreach {
        $_.groups[1].value -replace '####',($_.groups[2].value)
        }) -join '' |
        Set-Content $_.FullName
     }
    

    【讨论】:

    • 适用于该实例,但我需要它在多个文件中执行此操作。打开 .txt 搜索 ====-1234 并将 #### 替换为数字。一个文件可以有多个组,目录可以有多个文件。
    • 留下一个例子。它处理每个文件的多个实例。你只需要为你的文件集合设置一个循环。
    • 我尝试了 sn-p,但在 -Raw 行出现错误:Get-Content : A parameter cannot be found that matches parameter name 'raw'. At C:\Users\NX07934\Documents\Projects\23045\Docs\SampleData\PowerShellTest_Regex.ps1:11 char:32 + $text = Get-Content $_ -raw <<<< + CategoryInfo : InvalidArgument: (:) [Get-Content], ParameterBindingException + FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.GetContentCommand
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-08
    • 2020-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多