【问题标题】:powershell - search from a file & replace into another filepowershell - 从文件中搜索并替换到另一个文件中
【发布时间】:2014-05-26 05:34:59
【问题描述】:

我想从一个文件中搜索一组字符串并替换到另一个文件中。例如:

文件 A.txt(搜索模式)

文件 B.txt(实际文件)

所以,在这里我想将文件 A 中给出的所有字符串替换为文件 B(将文件 A 的所有行与文件 B 的每一行进行比较/替换)。我想以简单的方式实现,也许使用 foreachobject 循环。请帮帮我??

【问题讨论】:

  • 您指定了搜索模式的源(文件 A)和目标文件(文件 B),但是您要替换模式的字符串的源在哪里?或者你想完全删除那些...?

标签: powershell


【解决方案1】:

为了获得良好的学习体验,我在下面创建了一个 cmdlet。内联 cmets 应该能够指导您如何完成它。

function Get-ReplacedText
{
    [CmdletBinding()]
    Param
    (
        # Path containing the text file to be searched.
        $FilePath,

        # Path containing the patterns to be searched and replaced.
        $SearchPatternFilePath
    )

    # Patterns will be read in full for fast access.
    $patterns = Get-Content -Path $SearchPatternFilePath 

    # Use the StreamReader for efficiency.
    $reader = [System.IO.File]::OpenText($FilePath)

    # Open the file
    while(-not $reader.EndOfStream)
    {
        $line = $reader.ReadLine()

        foreach ($pattern in $patterns) {

            $search, $replacement = $pattern.Split()

            # Replace any searched text that exist with replacement.
            $line = $line -replace $search, $replacement
        }

        # Get the replaced line out of the pipeline.
        $line
    }

    #Close the file.
    $reader.Close()
}

请注意,您从中读取模式的文件应该是这样构造的,其中搜索模式和替换文本之间有一个空格。此外,搜索模式可以是 Regexp 格式。

searchpattern1 replacement1
searchpattern2 replacement2

最后,一个使用 cmdlet 的示例,

Get-ReplacedText -FilePath txtfile.txt -SearchPatternFilePath searchpattern.txt | Out-File -FilePath result.txt -Encoding ascii

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-11
    • 2019-03-06
    • 2018-01-22
    • 2019-11-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多